3

Why can't I trigger the submit button's closest form in this example below?

html,

<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>

jquery,

$('input[type=submit]').click(function(){

    $(this).closest('form').unbind('submit').submit(function(){
           alert("hello world");
        return false;
    });
    return false;
});

I should get the alert message, but I can't. What have I done wrong?

the jsfiddle

4

2 回答 2

3

哇,这么多的冒泡事件...

您不断返回 false 并绑定和取消事件...这不起作用,但您可以简单地将submit按钮更改为 normal button,例如:

<form name="input" action="html_form_action.asp" method="get">
    Username: <input type="text" name="user" />
    <input type="button" value="Submit" class="btn-submit" />
</form>

和写

$(".btn-submit").click(function() {
    $(this).prop("disabled", true); // dont allow more clicks 
    alert('about to submit...');
    $(this).closest("form").submit();
    alert('done!');
});

JsBin 中的演示:http : //jsbin.com/elokov/1/


使用 ajax 调用提交表单

$(".btn-submit").click(function(evt) {
    $(this).prop("disabled", true); // dont allow more clicks 
    alert('about to submit...');

    var frm = $(this).closest("form"); // our form

    $.ajax(
        type: frm.attr("method"),
        url:  frm.attr("action"),
        data: frm.serialize(),
        success: function(data) {
            alert('all went well');
        },
        success: function(jqXHR, textStatus) {
            alert('err, something messed up! ' + textStatus);
        }
    );

    return false; // or use evt.preventDefault();
});
于 2013-07-13T19:20:23.430 回答
0

因为您的代码只是绑定了提交事件,但它没有触发提交事件。如果您只是想阻止表单提交和更改,那么这应该足够了

$('input[type=submit]').click(function (e) {
    alert("hello world");
    return false;
});
于 2013-07-13T19:19:23.860 回答