在按钮上使用 formaction 属性时如何在提交时获取表单操作
How to get the form action on submit when using the formaction attribute on a button
A <form>
有不同的按钮。在提交事件中,我想知道单击了哪个按钮。我想到按钮上的 formaction
属性可以用于此目的。在 MDN 上,它表示 formaction
属性:
Overrides the action attribute of the button's form owner.
但是在获取表单操作时,此值不会根据 formaction
更改。那么我怎样才能得到 formaction
的值,或者你有解决这个问题的任何其他建议吗?
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.target.action);
switch (e.target.action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>
查看 e.submitter
。它会给你提交表单的元素
将 value
添加到 button
,然后使用 submitter
,如下所示。
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.submitter.value);
switch (e.submitter.value) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button value="a">A</button>
<button value="b">B</button>
</form>
如果 formaction
附加到按钮以覆盖提交事件,那么您需要在提交事件发送后获取具有当前焦点的元素,因此要获取活动元素值,请使用 document.activeElement
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let action = document.activeElement.getAttribute("formaction");
console.log(action);
switch (action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default" method="get">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>
A <form>
有不同的按钮。在提交事件中,我想知道单击了哪个按钮。我想到按钮上的 formaction
属性可以用于此目的。在 MDN 上,它表示 formaction
属性:
Overrides the action attribute of the button's form owner.
但是在获取表单操作时,此值不会根据 formaction
更改。那么我怎样才能得到 formaction
的值,或者你有解决这个问题的任何其他建议吗?
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.target.action);
switch (e.target.action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>
查看 e.submitter
。它会给你提交表单的元素
将 value
添加到 button
,然后使用 submitter
,如下所示。
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.submitter.value);
switch (e.submitter.value) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button value="a">A</button>
<button value="b">B</button>
</form>
如果 formaction
附加到按钮以覆盖提交事件,那么您需要在提交事件发送后获取具有当前焦点的元素,因此要获取活动元素值,请使用 document.activeElement
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let action = document.activeElement.getAttribute("formaction");
console.log(action);
switch (action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default" method="get">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>