简体   繁体   中英

Trigger Click of Submit Button When Parent Is Clicked with jQuery

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.

HTML:

<div class="container">
    <input type="submit" value="OK">
</div>

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:

$('.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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