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');
});