jQuery event delegation for select/options in Chrome

為{幸葍}努か 提交于 2019-12-24 20:57:54

问题


I am trying to bind a simple click event to an the selected option of a pulldown.

$('select#myselect').delegate(':selected', 'click', function()  
{  
    alert('selected');  
});

This code works in Firefox, but not Chrome/Safari. Can I use the .delegate() to bind an option for a pulldown menu like this? If so, how? If not, what is the best alternate solution?

btw, jQuery Click on Event.. gives a potential solution using .change(), but I would like to manage all bindings with .delegate() if possible.


回答1:


The click event doesn't fire for <option> elements in these browsers, but whether your options are changing or not, it there's nothing different with:

$('#myselect').change(function() {  
  alert('selected, my new value is: ' + $(this).val());  
});

It comes down to this, there's no need for .delegate() here. .delegate() is used to listen for events that bubble up from descendant elements that may change or are very numerous, when the element itself won't be going anywhere (e.g. replace via AJAX). .live() works in a very similar way, it just listens all the way up on document.

I don't know a better way to explain it other than this: your current usage is not at all what .delegate() is for, it's intended to solve a different problem. You should use .change() here.



来源:https://stackoverflow.com/questions/3419038/jquery-event-delegation-for-select-options-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!