给定一个下拉列表,是否有任何方式可以订阅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"
答案 0 :(得分:1)
这适用于所有浏览器(包括资源管理器,这是关于此类事情的bug。)。
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'});
});