Maximum range error on click event in jQuery
I have a reproducable error here, where I run into a Uncaught RangeError: Maximum call stack size exceeded
It's just a click event I call onto a link.
My HTML:
<div id="box">
<a href="#">test</a>
</div>
My Javascript:
$('#box').click(function() {
("a", $(this)).click();
});
Now, clicking the #box
leads t开发者_高级运维o an error.
http://jsfiddle.net/DMAMv/2/
You should stop the propagation with stopImmediatePropagation(), otherwise you have too much rcursion
$('#box').click(function() {
$("a:first", this).click();
});
$('a').click(function(e){
e.stopImmediatePropagation();
alert('hi');
});
fiddle http://jsfiddle.net/DMAMv/8/
That's because it is recursively triggering the click event. This is caused by two problems.
The first is this innocent looking line:
("a", $(this)).click(); # note the missing $ at the beginning
That essentially reduces to $(this).click()
(because the comma operator evaluates both operands and returns the second one) and so your click event on #container
triggers itself. Consider the following examples - http://jsfiddle.net/2VnbG/ and http://jsfiddle.net/2VnbG/1/ - notice how the parent div is targetted when the $
is missing.
Prepend the line with the missing $
to solve that issue, i.e. $("a", $(this)).click();
The next problem is that a click event on the anchor will bubble up to the parent object (in your case, #container
). If the parent has a bound function on the click event which triggers a new event, then the cycle is going to repeat infinitely.
To solve that, use event.stopPropagation()
to stop the event from bubbling up the DOM tree.
Here's an example with the above fixes in place: http://jsfiddle.net/DMAMv/9/
mine was a list item in a dropdown so i wanted the event to keep bubbling so the dropdown would be closed. this is the solution i used:
$('div#outer').click(function (e) {
if (e.target == e.currentTarget) // prevents bubbled events from triggering
$($(e.currentTarget).children()[0]).trigger('click');
});
精彩评论