2011-06-06 73 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) {...