2010-10-26 23 views
0

我有組合框(事實上,其中幾個),動態添加元素。jQuery - 如何在combobox上實現live()?

使用jQuery,我不知道如何實現函數將返回我在組合所選項目的ID ...

我知道,它有使用.live東西(是),像

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

...但我不知道如何在這裏實現它。

tnx in adv!

回答

1

您正在尋找這樣的事情?

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

使用上的選擇元素的子元素(又名選項)的:selected選擇

$(".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
$(".foo").live("change", function() { 
    alert($(this).attr("id")); // Id of the element 
}); 
+0

我想這就是答案,如果他想選擇的id但我認爲如果你仔細閱讀,他正在尋找所選選項的價值 – hunter 2010-10-26 18:21:51

1

您可以使用$(this).val()找到觸發事件的元素的值。

看來別人已經打敗了我。我和@John和@Daniel一樣。

這裏是一個jsfiddle來測試它jsfiddle

需要注意的一件事是,live不支持所有瀏覽器中的change方法(如IE 6到8)。解決此

一種方法是使用委託方法,我已經證明here

它看起來是這樣的:

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