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.
-
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
3 Answers
Reset to default 5Because in every click
event, you call click
again, resulting in never ending recursion.
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
.
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();
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744765787a4592450.html
评论列表(0条)