关于项目在下拉列表中添加事件(选项选择器)
问题描述:
给定一个下拉列表,是否有任何方法可以订阅JavaScript,甚至在将新项目添加到列表时会触发一个JavaScript?关于项目在下拉列表中添加事件(选项选择器)
我想类似以下工作
$("select").itemAdded(function(value, text) {
alert(text + " has just been added to the list of options");
});
$("select").append($("<option></option").val("1").html("Something"));
//results in alert of "Something has just been added to the list of options"
答
这应该对所有的浏览器(包括资源管理器,这是一个关于这样的事情开溜)工作。
var option = document.createElement("option");
option.text = 'The visual value';
option.value = 'Th submitted value';
$("select")[0].options.add(option);
编辑: 我可能应该停止为松弛,给你完整的代码,使这项工作作为一个jQuery插件。
(function($) {
$.fn.add_option = function(options) {
var config = {
value:0,
text:0
}
config = $.extend(config, options);
return this.each(function() {
var option = document.createElement("option");
option.text = config.text;
option.value = config.value;
$(this)[0].options.add(option);
alert(config.text+ " has just been added to the list of options");
}
}
})(jQuery);
$(document).ready(function() {
$('#id_of_select_dropdown').add_option({text:'My new text value', value:'new'});
});
不完全确定为什么有人认为这应该是负面投票 - 我写的东西没有什么错,据我所知。 – Steerpike 2009-02-18 16:52:06