jQuery.live() Handlers Firing Multiple Times
我必须根据某些服务响应动态生成一些按钮,并且还必须在单击这些按钮时附加一些处理程序。因此,我正在使用
但是当我使用
你们可以帮我吗,谢谢。
$()。live()在jQuery 1.7中已贬值,在1.9中已删除
或尝试类似
的方法
1 2 3 | $('#button').die('click').live('click', function(e) { alert('Button click'); }); |
关注jquery网站jquery.live():
Attach an event handler for all elements which match the current
selector, now and in the future.
这是指:与live一起附加的事件将应用于具有相同选择器的所有元素。因此,您必须检查element的事件,并在不可用时附加新元素。
1 2 3 4 5 6 7 8 9 10 11 | $("SELECTOR").live('click',function(e){ //check the event is already set e.preventDefault(); if(e.handled === true) return false; e.handled = true; //Do something here //YOUR CODE HERE return false; }); |
我正在使用Jquery 1.11.min,这对我有用:
1 2 3 4 5 | $(document).ready(function() { $('#button_id').off('click').on('click', function() { //enter code here }); }); |
这不是问题的直接答案。但是,值得注意的是。
.live()与.bind()
@jAndy说:
You should consider to use .delegate() instead of .live() whereever possible. Since event delegation for .live() always targets the body/document and you're able to limit"bubbling" with .delegate().
然后从jQuery:
As of jQuery 1.7,
.delegate() has been superseded by the.on() method.
For earlier versions, however,.delegate() remains the most effective means to use event delegation.
参考:
尝试此操作,在removeButton函数上,尝试取消绑定click事件。并在再次添加时重新绑定。
1 2 3 4 5 6 7 8 9 10 11 | function removeButton(){ $("button").unbind("click"); //code for removing button } function addButton(){ //code for adding button $("button").live("click", function(){ //your code }); } |