javascript 通过JQuery提交表单时如何点击提交按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15773957/
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
How to get clicked submit button when submitting a form via JQuery
提问by Ali Bassam
I have a form with 2 submit buttons.
我有一个带有 2 个提交按钮的表单。
<form class="myForm">
<!-- Some Inputs Here -->
<input type="submit" name="firstSubmit" value="first submit" />
<input type="submit" name="secondSubmit" value="second submit" />
</form>
I am submitting this form via JQuery.
我正在通过 JQuery 提交此表单。
$(".myForm").submit(function(){
var submitButton = ? //I need to catch the submit button that was clicked
});
How can I know which submit button was clicked?
我怎么知道点击了哪个提交按钮?
回答by adeneo
$('input[type="submit"]').on('click', function(){
$('.myForm').data('button', this.name);
});
$(".myForm").on('submit', function(){
var submitButton = $(this).data('button') || $('input[type="submit"]').get(0).name;
});
回答by Marcos
Try this:
试试这个:
$(".myForm").submit(function(){
var submitButton = $(":focus", this);
});
回答by Tobias Buschor
There is now a standard submitter
property in the submit event.
Already implemented in firefox!
现在submitter
提交事件中有一个标准属性。
已经在火狐中实现了!
document.addEventListener('submit',function(e){
console.log(e.submitter)
})
in jQuery you just write
在 jQuery 中,您只需编写
$(".myForm").on('submit', function(e){
e.originalEvent.submitter
});
for browsers not supporting it use this polyfill:
对于不支持它的浏览器,请使用这个 polyfill:
!function(){
var lastBtn = null
document.addEventListener('click',function(e){
if (!e.target.closest) return;
lastBtn = e.target.closest('button, input[type=submit]');
}, true);
document.addEventListener('submit',function(e){
if (e.submitter) return;
var canditates = [document.activeElement, lastBtn];
for (var i=0; i < canditates.length; i++) {
var candidate = canditates[i];
if (!candidate) continue;
if (!candidate.form) continue;
if (!candidate.matches('button, input[type=button], input[type=image]')) continue;
e.submitter = candidate;
return;
}
e.submitter = e.target.querySelector('button, input[type=button], input[type=image]')
}, true);
}();