表单jquery防止默认

时间:2011-11-01 21:52:18

标签: javascript jquery

我想阻止表单提交,但是执行其他表单处理程序,preventDefault会停止提交。

这是一个例子:

<form id="example">
    <input type="text" name="name" />
</form>

<form id="example2">
    <input type="text" name="name2" />
</form>

/* generic form handling */
$('form').submit(function(e) {
    alert('hello');
});

/* 
    specific example 
    i want this handler to prevent the form from submitting normally, but at the same time, i want it to execute the above code with the alert "hello"
*/
$('form#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

2 个答案:

答案 0 :(得分:2)

尝试返回false(http://api.jquery.com/submit/声明返回false将停止提交):

$('form#example').submit(function(e) {
    return false;
});

答案 1 :(得分:1)

如果替换

会发生什么
$('form#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

通过

$('#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

没有测试,逻辑告诉我这是有意义的;您只能阻止该特定表单上的操作。还是我误解了你的问题?