問題描述
很驚訝,我在從 JS 提交表單時遇到了這個奇怪的問題.
Surprised, I am encountering this weird issue while submitting form from JS.
考慮一個使用 submit
按鈕和 anchor link
Consider a simple form submitted using two ways from a submit
button and an anchor link
<form method="POST" action="page.html" name="foobar" id="test">
<input type="text" />
<input type="submit" />
</form>
<a href="#" onclick="document.getElementById('test').submit();">click me</a>
捕獲提交事件的函數
document.getElementById('test').onsubmit = function() {
// Same result with
// * document.foobar.onsubmit
// * document.forms['foobar'].onsubmit
alert('foobar');
return false;
}
現在,當通過單擊 submit
按鈕提交表單時,我會收到警報,但 單擊鏈接時不會.為什么會這樣?
Now, when the form is submitted from clicking the submit
button I get the alert, but not when clicking the link. Why is this doing so?
小提琴顯示問題
推薦答案
為了提供一個合理確定的答案,HTML 表單提交算法 第 5 項指出,表單僅在未提交時才調度提交事件通過調用提交方法(這意味著它僅在通過按鈕或其他隱式方法提交時才調度提交事件,例如在焦點位于輸入類型文本元素上時按 Enter).
To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).
如果沒有發送提交事件,則不會調用提交處理程序.
If no submit event is dispatched, then the submit handler won't be called.
這與 DOM 2 HTML 不同規范,它說提交方法應該做提交按鈕所做的事情.
That is different to the DOM 2 HTML specification, which said that the submit method should do what the submit button does.
所以如果你想使用腳本提交表單,你應該手動調用提交監聽器.如果偵聽器是使用 addEventListener 添加的,那么您需要記住并調用它,因為您無法通過檢查表單來發現它(如下所示).
So if you want to use script to submit a form, you should manually call the submit listener. If the listener was added using addEventListener, then you'll need to remember that and to call it since you can't discover it by inspecting the form (as suggested below).
如果監聽器是內聯設置的,或者添加到 DOM onsubmit 屬性中,你可以這樣做:
If the listener is set inline, or added to the DOM onsubmit property, you can do something like:
<form onsubmit="return validate(this);" ...>
...
</form>
<button onclick="doSubmit()">submit form</button>
<script>
function doSubmit() {
var form = document.forms[0];
if (form.onsubmit) {
var result = form.onsubmit.call(form);
}
if (result !== false) {
form.submit();
}
}
</script>
如果您需要傳遞參數或做其他事情,生活會更加艱難.
Life is tougher if you need to pass parameters or do other things.
這篇關于使用 submit() 從鏈接提交的表單無法被 onsubmit 處理程序捕獲的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!