jQuery - 如何在组合框上实现live()?

时间:2010-10-26 18:16:37

标签: jquery combobox live

我有组合框(事实上,其中有几个),动态添加了元素。

使用jQuery,我不知道如何实现将返回在组合中选择的项目ID的函数...

我知道必须使用.live(),比如

$(".foo").live("change", function() {
do something;
});

...但我不知道如何在这里实施。

tnx in adv!

4 个答案:

答案 0 :(得分:1)

在select元素的子元素上使用:selected选择器(a.k.a. options)

$(".foo").live("change").function(){ 
    var val = $(".foo").find(":selected").val();
    // pass val to some other method for work
});

http://api.jquery.com/selected-selector/

答案 1 :(得分:1)

你在找这样的东西吗?

$(".foo").live("change", function() {
  $(this).val(); // value of the changed item
});

答案 2 :(得分:1)

$(".foo").live("change", function() {
   alert($(this).attr("id")); // Id of the element
});

答案 3 :(得分:1)

您可以使用$(this).val()查找触发事件的元素的值。

似乎其他人已经打败了我。我跟@John和@Daniel一样。

这是一个jsfiddle来测试它jsfiddle

有一点需要注意的是,live不支持所有浏览器中的更改方法(例如IE 6到8)。

解决此问题的一种方法是使用委托方法,我已经演示了here

看起来像是:

$(parentElement).delegate(selector, 'change', function() {
    //do something interesting here
    //$(this).val() still works.
});
相关问题