最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is my alert showing more than once? - Stack Overflow

programmeradmin1浏览0评论

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 what live 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
 |  Show 3 more ments

2 Answers 2

Reset to default 3

It 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');
});
发布评论

评论列表(0)

  1. 暂无评论