简体   繁体   English

jquery 多次告警

[英]jquery alerts several times

Why does the following code cause jquery to alert 3 times?为什么下面的代码会导致 jquery 警告 3 次?

.note_text is a class within .note_content . .note_text是 .note_content 中的.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');
         }   
      });

   });

When the outer div is highlighted I want the inner div (which contains the text) to be focused on.当外部 div 突出显示时,我希望内部 div(包含文本)被关注。

This is due to action bubbling.这是由于动作冒泡。

Adding a event.stopPropagation();添加一个event.stopPropagation(); should fix that.应该解决这个问题。

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

$(note_text).blur(function() {

That line binds an event handler.该行绑定了一个事件处理程序。 Every time the element is blurred, that handler will run.每次元素模糊时,该处理程序都会运行。 You assign a new handler every time the click handler on .note_content is triggered, so you will have multiple alerts.每次触发.note_content上的单击处理程序时,您都会分配一个新的处理程序,因此您将有多个警报。

The way around this is to store data on the element, rather than in a closure.解决这个问题的方法是将数据存储在元素上,而不是在闭包中。

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

This way the handlers are only bound once.这样处理程序只绑定一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM