admin管理员组

文章数量:1391747

Check this link: jsfiddle example

When a div is clicked I want the link inside to trigger a click event. but the console shows that the click event keeps triggering until the browser crashes. 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. This function is intended to work on mobile devices.

Check this link: jsfiddle example

When a div is clicked I want the link inside to trigger a click event. but the console shows that the click event keeps triggering until the browser crashes. 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. This function is intended to work on mobile devices.

Share Improve this question asked Mar 27, 2013 at 13:59 halliewuudhalliewuud 2,7857 gold badges31 silver badges41 bronze badges 2
  • 1 What is the goal of triggering the click event of <a> element? – VisioN Commented Mar 27, 2013 at 14:05
  • Timestamp: 27/03/2013 19:34:06 Error: too much recursion Source File: code.jquery./jquery-1.9.1.js Line: 2749 – ssilas777 Commented Mar 27, 2013 at 14:05
Add a ment  | 

3 Answers 3

Reset to default 5

Because in every click event, you call click again, resulting in never ending recursion.

Since your click handler is on divs with the box class, clicking on anything inside of those divs will cause the click event on the div.

It seems like you're wanting a click on the div to follow the link? Instead of triggeing a click on the link, you could do this:

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. 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.

One more alternate solution would be (remended),

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

本文标签: javascriptTriggering click event crashes the browserStack Overflow