admin管理员组文章数量:1435859
I have this jQuery code:
$("div.note a").live("click", function(e) {
e.preventDefault();
alert('test');
});
<div id="note_list">
<div class="note">
Text 1
<a href="">X</a>
</div>
<div class="note">
Text 2
<a href="">X</a>
</div>
<div class="note">
Text 3
<a href="">X</a>
</div>
</div>
Could someone tell me why the alert shows 3 times? It works fine in Chrome but not in Firefox.
I have this jQuery code:
$("div.note a").live("click", function(e) {
e.preventDefault();
alert('test');
});
<div id="note_list">
<div class="note">
Text 1
<a href="">X</a>
</div>
<div class="note">
Text 2
<a href="">X</a>
</div>
<div class="note">
Text 3
<a href="">X</a>
</div>
</div>
Could someone tell me why the alert shows 3 times? It works fine in Chrome but not in Firefox.
Share Improve this question edited Oct 19, 2011 at 13:57 Andy E 345k86 gold badges482 silver badges451 bronze badges asked Oct 19, 2011 at 13:54 DailDail 4,62816 gold badges77 silver badges113 bronze badges 8-
3
It appears only once for me: jsfiddle/s2ZAz
->
If there is a problem it is somewhere else in your code. Maybe you are adding the elements dynamically and binding the event handler every time? Then you did not understand whatlive
is doing: api.jquery./live – Felix Kling Commented Oct 19, 2011 at 13:56 - might be you are assigning live event multiple times.try to unbind click event before assigning. – sathis Commented Oct 19, 2011 at 13:57
- @sathis, yes I use live because the cose is loaded doing .html(html_code). Why .live() is not good? I mean...what do i have to unbind the event and then use live again? – Dail Commented Oct 19, 2011 at 14:01
-
@Dail: No,
live
is good when it is used correctly. But as it stands, we cannot reproduce your problem which either means you don't have a problem or you provide more code which might be related to the problem or you have to solve it by yourself. – Felix Kling Commented Oct 19, 2011 at 14:04 - @dail i suspect you are assigning a function to click event inside another event i.e every time you are assigning a function to click event without clearing the previous one. – sathis Commented Oct 19, 2011 at 14:06
2 Answers
Reset to default 3It is called onetime, in your case you can stop multiple event call by e.stopImmediatePropagation();
$("div.note a").live("click", function(e) {
e.stopImmediatePropagation();
e.preventDefault();
alert('test');
});
Try this
$("div.note a").die('click').live("click", function(e) {
e.preventDefault();
alert('test');
});
本文标签: javascriptWhy is my alert showing more than onceStack Overflow
版权声明:本文标题:javascript - Why is my alert showing more than once? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745669899a2669505.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论