I have a submit button wrapped in a div. I want to trigger a click event on the submit button when the div is clicked. The problem is, this click event bubbles up and causes a stack overflow/infinite loop. When I try to stop propagation of the child click event, the issue is not resolved.
我有一个div包含的提交按钮。我想在单击div时触发提交按钮上的单击事件。问题是,此单击事件冒泡并导致堆栈溢出/无限循环。当我尝试停止传播子点击事件时,问题仍未解决。
HTML:
HTML:
<div class="container">
<input type="submit" value="OK">
</div>
jQuery:
jQuery的:
$('.container').click(function () {
var input = $(this).find('input');
input.trigger('click');
input.click(function(event) {
event.stopPropagation();
});
});
This still causes the stack overflow error. So does returning false:
这仍然会导致堆栈溢出错误。返回false也是如此:
$('.container').click(function () {
var input = $(this).find('input');
input.trigger('click');
return false;
});
Help appreciated!
帮助赞赏!
1 个解决方案
#1
4
Don't bind button click event inside container click one. It should be this way
不要在容器内部单击按钮单击事件。应该是这样的
$('.container').click(function() {
var input = $(this).find('input');
input.trigger('click');
});
$('input').click(function(e) {
e.stopPropagation();
alert('button clicked');
});
The problem with your code is that container click triggers inner button click before its respective click handler is even registered, so it have no chance to stop event bubbling.
您的代码的问题是容器单击会在其各自的单击处理程序甚至已注册之前触发内部按钮单击,因此它没有机会停止事件冒泡。
#1
4
Don't bind button click event inside container click one. It should be this way
不要在容器内部单击按钮单击事件。应该是这样的
$('.container').click(function() {
var input = $(this).find('input');
input.trigger('click');
});
$('input').click(function(e) {
e.stopPropagation();
alert('button clicked');
});
The problem with your code is that container click triggers inner button click before its respective click handler is even registered, so it have no chance to stop event bubbling.
您的代码的问题是容器单击会在其各自的单击处理程序甚至已注册之前触发内部按钮单击,因此它没有机会停止事件冒泡。