jquery多次警报

时间:2011-06-06 19:56:06

标签: jquery

为什么以下代码会导致jquery发出3次警报?

.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突出显示时,我想要关注内部d​​iv(包含文本)。

2 个答案:

答案 0 :(得分:3)

这是由于动作冒泡。

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

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

答案 1 :(得分: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');
    }
});

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