简体   繁体   English

触发点击事件使浏览器崩溃

[英]Triggering click event crashes the browser

Check this link: jsfiddle example 检查此链接: jsfiddle示例

When a div is clicked I want the link inside to trigger a click event. 单击div时,我希望其中的链接触发click事件。 but the console shows that the click event keeps triggering until the browser crashes. 但控制台显示click事件一直触发,直到浏览器崩溃为止。 Why is this happening? 为什么会这样呢? And whats the solution? 解决方案是什么?

The real div's has alot of content inside of it so I don't want the <a> tag to cover the whole div or wrap the div inside a <a> tag. 真正的div内部有很多内容,因此我不希望<a>标记覆盖整个div或将div包裹在<a>标记内。 This function is intended to work on mobile devices. 此功能旨在在移动设备上工作。

Because in every click event, you call click again, resulting in never ending recursion. 因为在每次click事件中,您都会再次调用click ,导致永无止境的递归。

Since your click handler is on div s with the box class, clicking on anything inside of those div s will cause the click event on the div . 由于点击处理程序是div s的中box类,点击这些内部任何div旨意导致click的事件div

It seems like you're wanting a click on the div to follow the link? 您似乎要单击div来跟随链接? Instead of triggeing a click on the link, you could do this: 您无需执行以下操作click触发链接:

window.location = $(this).find(".link").attr("href");

Try this. 尝试这个。 It stops the infinite loop. 它停止了无限循环。 But a better question is why do this? 但是更好的问题是为什么这样做?

$(".box").click(function(e){
    console.log("clicked");
    $(this).find(".link").trigger("click");
});

$(".link").click(function(e){
    e.stopPropagation();
});

When you trigger a click on ".link", that event bubbles up to its parent and eventually reaches ".box" again. 当您触发对“ .link”的单击时,该事件会冒泡直至其父事件并最终再次到达“ .box”。 Hence going into recursion. 因此进入递归。 To prevent this, You could do something like 为防止这种情况,您可以执行以下操作

$(".box").click(function(e){
    if(e.currentTarget == e.target)
    {    
        console.log("clicked");
        $(this).find(".link").trigger("click");
    }
});

The e.target is the element where the event occured and the e.currentTarget is the element on which the event was bound. e.target是事件发生的元素,而e.currentTarget是事件绑定的元素。

One more alternate solution would be (recommended), (推荐)另一种替代解决方案,

$(".box").click(function(e){
    console.log("clicked");
    $(this).find(".link").trigger("click");       
});
$(".link").click(function (e)
{
    /*This would prevent a click triggered on ".link" to propagate upto its parent i.e ".box" */
    e.stopPropagation();
});

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

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