提交时的 jQuery 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22590296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:00:09  来源:igfitidea点击:

jQuery document on submit

jquerysubmit

提问by Klaaz

I am using jQuery to post forms through ajax like this:

我正在使用 jQuery 通过 ajax 发布表单,如下所示:

$(document).on("submit",this.id, function (e) {
    // Do stuff 
})

This way it takes the ID of the form and uses the ID to handle all the necessary things with the data from the different forms on different pages.

通过这种方式,它获取表单的 ID 并使用该 ID 来处理来自不同页面上不同表单的数据的所有必要的事情。

This works prefect with one form on the page. When I have multiple forms (with unique ID's) it fails, does not respond/trigger anymore.

这适用于页面上的一个表单。当我有多个表单(具有唯一 ID)时,它会失败,不再响应/触发。

I know I can enter the ID of the form myself and use multiple $(document).on... in my jQuery but I really like the approach I am using now.

我知道我可以自己输入表单的 ID 并在我的 jQuery 中使用多个 $(document).on... 但我真的很喜欢我现在使用的方法。

Is there a way to solve this?

有没有办法解决这个问题?

回答by Shadow Wizard is Ear For You

You don't need to pass or use the ID, you probably have scope problem.

您不需要传递或使用 ID,您可能有范围问题。

Use such code instead which is more flexible:

改用这样的代码,它更灵活:

$(document).on("submit", "form", function (e) {
    var oForm = $(this);
    var formId = oForm.attr("id");
    var firstValue = oForm.find("input").first().val();
    alert("Form '" + formId + " is being submitted, value of first input is: " + firstValue);
    // Do stuff 
    return false;
})

Using the $(this)you get reference to the form being submitted, inside the event handler. You can then use it as you wish, instead of finding the form from scratch.

使用$(this)您可以在事件处理程序中获取对正在提交的表单的引用。然后您可以随意使用它,而不是从头开始查找表单。

Live test case.

现场测试用例