JQuery - 将更改事件添加到下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/836694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery - Adding change event to dropdown
提问by Keith Barrows
The underlying HTML for my drop down has a chance of changing and I was trying to set it up using the .live
option rather than the .change
option. it does not work for me.
我的下拉列表的底层 HTML 有可能发生变化,我试图使用.live
选项而不是.change
选项来设置它。它对我不起作用。
What I currently have is:
我目前拥有的是:
$("#ItemsPerPage").change(function(e) { return updatePaging(); });
Unfortuantely, if I update this control via $.ajax
it loses the event definition. What I tried, and is not working, is:
不幸的是,如果我通过$.ajax
它更新此控件会丢失事件定义。我尝试过但不起作用的是:
$("#ItemsPerPage").live("change", function(e) { return updatePaging(); });
Any thoughts?
有什么想法吗?
回答by Jed Schmidt
Instead of rebinding the <select>
every time, you're better off just swapping its contents (the list of <option>
elements) instead.
与其<select>
每次都重新绑定,不如交换它的内容(<option>
元素列表)。
So use this as you already are:
所以像你一样使用它:
$("#ItemsPerPage").change(function(e) { return updatePaging(); });
but when you update it, just swap out its contents ( where newSelectElement
is the new <select>
element):
但是当你更新它时,只需换出它的内容(newSelectElement
新<select>
元素在哪里):
function updateItemsPerPage( newSelectElement ) {
$("#ItemsPerPage").empty().append( newSelectElement.childNodes );
}
This way, the binding won't need to be refreshed because the node itself isn't swapped.
这样,绑定就不需要刷新,因为节点本身没有交换。
回答by KyleFarris
To elaborate on samiz's suggestion, you would need to do something like this:
要详细说明 samiz 的建议,您需要执行以下操作:
$(function() {
bind_items_per_page();
});
function bind_items_per_page() {
$("#ItemsPerPage").unbind('change').bind('change',function() {
updatePaging();
});
}
function updatePaging() {
$.post('/some/script',{foo:'bar',bar:'foo'},function(data) {
/* what ever you need to do */
// And assuming what ever you did above changed your select box...
bind_items_per_page();
});
}
回答by samiz
The change event is not supported by live(). How about running a function at the end of every AJAX call that reassigns the event definition?
live() 不支持 change 事件。在每次 AJAX 调用结束时运行一个重新分配事件定义的函数怎么样?