2011-06-06 52 views
0

为什么下面的代码会导致jquery提醒3次?jquery多次提醒

.note_text.note_content中的一类。

$('.note_content').click(function() { 
     var note_text = $(this).find(".note_text"); 
     $(note_text).focus(); 

     // save its contents: 
     var original_text = note_text.html(); 

     $(note_text).blur(function() { 
     if (note_text.html() !== original_text) 
     { 
      alert('Not the same'); 
     } 
     }); 

    }); 

当外部div突出显示时,我想要内部div(其中包含文本)被关注。

回答

1
$(note_text).blur(function() { 

该行结合事件处理程序。每当元素模糊时,该处理程序将运行。每次触发.note_content的点击处理程序时,都会分配一个新处理程序,因此您将有多个警报。

解决方法是将数据存储在元素上,而不是封闭。

$('.note_content').click(function() { 
    $(this).find('.note_text').data('oldText', node_text.html()).focus(); 
}); 
$('.note_text').blur(function() { 
    if ($(this).html() !== $(this).data('oldText')) { 
     alert('not the same'); 
    } 
}); 

这样处理程序只绑定一次。

3

这是由于行动冒泡。

添加一个event.stopPropagation();应该解决这个问题。

(记住 - $('.note_content').click(function(event) {...