Javascript jquery click() 在提交按钮中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26746982/
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-22 23:19:23  来源:igfitidea点击:

jquery click() in submit button

javascriptjqueryformsclicksubmit

提问by iteam

I have a .click() function on a submit button in a form:

我在表单中的提交按钮上有一个 .click() 函数:

$("#submitId").click(function () {
    $('#hiddenInput').val(someVariable);
});

It works like a charm. When the submit button is clicked the click() function fills the hidden input variable and then the whole form gets submitted. The server then receives the hidden input with the refreshed content.

它就像一个魅力。单击提交按钮时,click() 函数会填充隐藏的输入变量,然后提交整个表单。服务器然后接收带有刷新内容的隐藏输入。

My question is: will it always work? Is there any danger that, by some reason not yet known to me, the submit operation gets executed first and the click() function later? I want to make sure the hidden input always gets refreshed.

我的问题是:它会一直有效吗?由于某种我还不知道的原因,是否有任何危险,提交操作先执行,然后单击()函数?我想确保隐藏的输入总是被刷新。

回答by PeterKA

When working with forms, it's alwaysadvisable to let the submitbutton do it's job: TRIGGER THE FORM'S SUBMIT EVENT... that's what it's meant for. Then you would listen for the submitevent on the formrather than the clickevent on the submitbutton.

在处理表单时,始终建议让submit按钮完成它的工作:触发表单的提交事件……这就是它的意义所在。然后,你将监听submit的事件form,而不是click在事件submit按钮。

You can use event.preventDefault()to prevent default submission of the form so that you can do some house keepingthen you can submit the form.

您可以使用event.preventDefault()来防止表单的默认提交,以便您可以做一些内务工作,然后您可以提交表单。

$("#submitId").closest('form').on('submit', function(event) {
    event.preventDefault();
    $('#hiddenInput').val(someVariable); //perform some operations
    this.submit(); //now submit the form
});

Or simply,

或者简单地说,

$('form').on('submit', function(event) {
    event.preventDefault();
    $('#hiddenInput').val(someVariable); //perform some operations
    this.submit(); //now submit the form
});

回答by Travis J

It would be best to attach the value update directly to the form's submit handler like this

最好像这样将值更新直接附加到表单的提交处理程序

$("#submitId").closest("form").submit(function () {
 $('#hiddenInput').val(someVariable);
});

回答by CmajSmith

I personally think it is safer to prevent submit, then set value of input needed and only then submit the form programmatically. Like:

我个人认为防止提交更安全,然后设置所需的输入值,然后才以编程方式提交表单。喜欢:

$("form").submit(function (e) {
    e.preventDefault();
    $('#hiddenInput').val(someVariable);
    $(this).submit();
});

回答by Justin C.

The .click() should always be run first.

.click() 应始终首先运行。