jQuery .submit() not triggering

2019-02-11 00:02发布

问题:

I've done a lot of searching but can't find out why my jQuery .submit() will not trigger. I've also tried with .click() for the submit button.

I've currently got a div template (includes a form):

<div class="reply-to-existing-message" style="display: none">
        <form class="reply-message-form">
            <textarea id="post-reply-message-textarea" name="PostReplyMessage[message]" rows="3" cols="40" style="resize: none"></textarea>
            <input class="reply-to-message-id" type="hidden" name="PostReplyMessage[id]" />
            <input class="post-reply-message-submit" type="submit" value="Reply"/>
        </form>
    </div>

I append this to a message using jQuery when the reply button is clicked (produces a drop down reply form so user can reply to a message). This works fine (double checked using firebug too).

However, my jQuery code doesn't produce the alert when I click on the submit button, so it's not even triggering. Could someone please explain why this is occurring, thanks! jQuery code:

$(document).ready(function() {
    $('.reply-message-form').submit(function() {
        alert('test');
        return false;
    }) ;
});

回答1:

If you're dynamically adding content, that static call to .submit() isn't going to work for you. That will only bind the event handler to the elements that matched the selector at the time it was run, so any elements added after that won't have the event handler bound.

The solution is event delegation, using the .on() function:

$(document).on('submit', '.reply-message-form', function(e) {
    alert('test');
    return false;
});

Ideally, rather than using document, you'd select the closest static (i.e. exists when the page loads) element that will contain all of your dynamic content.

Alternatively, if you're using a version of jQuery prior to 1.7 and therefore don't have access to the .on() function, you can use the .delegate() function instead:

$(document).delegate('.reply-message-form', 'submit', function(e) {
    alert('test');
    return false;
});


回答2:

For dynamically generated elements, you should delegate the events, you can use the on method, try the following:

$(document).ready(function() {
    $(document).on('click', 'input[type=submit]', function() {
        alert('test');
        return false;
    });
});