【问题标题】:jquery: stop infinite recursion?jquery:停止无限递归?
【发布时间】:2014-12-27 12:40:16
【问题描述】:

如何在此处停止无限递归,以便仅触发一次 mousedown 事件?它应该在一个单独的方法中吗?

$(document).on('mouseover',function (e) {
            $(e.target).mousedown(function(e){
                e.stopPropagation();
                console.log('clicked');
                $(e.target).trigger('mousedown'); //use hello(e); instead?
                return;
            })
});

$(document).on('mousedown', 'a', function(e){
  hello(e);
});

function hello(e){
console.log('got it');
}

这似乎触发了一个永无止境的循环。基本上我需要在鼠标下的当前元素上绑定一个 mousedown 处理程序,这将触发另一个处理程序能够处理的 mousedown 事件。

我这样做的原因是因为鼠标悬停在动态生成的元素上起作用,所以当这种情况发生时,我需要再次绑定处理程序,因为on 处理程序无法捕获新生成的元素。

【问题讨论】:

  • .mousedown() 处理程序的末尾,您再次间接调用它。这就是递归的来源。为什么已经处理完还要触发呢?
  • 因为它似乎没有在另一个处理程序中触发got it...应该在它自己的方法中以便直接调用它吗?
  • 我认为您根本不需要整个mouseover 处理程序,因为on 函数也会考虑动态添加的元素。目前,您正在停止事件传播,这会阻止事件到达第二个处理程序并打印“得到它”。
  • 如果目标不是<a>不会触发hello()。你应该详细说明你想要从这一切中得到什么
  • 您正在为您将鼠标拖过的每个元素添加一个新的 mousedown 事件。这太疯狂了。

标签: javascript jquery


【解决方案1】:

你让事情变得复杂了。想象一下,每次用户移动鼠标时,都会动态添加一个事件?

为什么不用类名来设计你的元素并在你的 mousedown 事件中使用它呢?这样,对 mousedown 的肯定调用将始终触发。

 $(".className").mousedown(function(e){
            console.log('clicked');
            return;
 })

--我这样做的原因是因为鼠标悬停在动态生成的元素上起作用,所以当这种情况发生时,我需要再次绑定一个处理程序,因为 on 处理程序无法捕获新生成的元素。 em>

如果你这么说,那么给你动态生成的元素添加一个类名,让你的 mousedown 事件绑定到它。

【讨论】:

    【解决方案2】:

    试试这样:

     $(document).on('mouseover',function (e) {
                    $(e.target).trigger('mousedown'); //use hello(e); instead?
                    return;
        
    });
    
     $(document).on('mousedown','a', function(e){
    	  hello(e);
    	});
    
    function hello(e){
    alert('got it');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#">hello</a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多