简体   繁体   English

使用jQuery单击父级时触发提交按钮的单击

[英]Trigger Click of Submit Button When Parent Is Clicked with jQuery

I have a submit button wrapped in a div. 我有一个包装在div中的提交按钮。 I want to trigger a click event on the submit button when the div is clicked. 单击div时,我想在“提交”按钮上触发click事件。 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. 当我尝试停止传播子点击事件时,此问题无法解决。

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! 帮助赞赏!

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. 您的代码的问题在于,容器单击甚至在其各自的单击处理程序尚未注册之前就触发了内部按钮单击,因此它没有机会停止事件冒泡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM