当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

http://jsfiddle.net/DMAMv/2/

I'm trying to achieve this: Unobstrusive click-able boxes

网友答案:

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');
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: