2009-02-18 63 views
1

給定一個下拉列表,是否有任何方法可以訂閱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" 

回答

1

這應該對所有的瀏覽器(包括資源管理器,這是一個關於這樣的事情開溜)工作。

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'}); 
}); 
+0

不完全確定爲什麼有人認爲這應該是負面投票 - 我寫的東西沒有什麼錯,據我所知。 – Steerpike 2009-02-18 16:52:06

相關問題