问题
I am trying to call a JavaScript function when the submit button of a form is clicked.
For some reason, the function is not called when it is named 'submit', but when it is named anything else, it works.
I should also note that when the button is taken out of the form tags, the function also works.
Can anyone please explain why when it is inside the form it does not work with that name?
Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function submit(){
console.log('test');
}
</script>
</head>
<body>
<form>
<input type="text"/>
<input type="submit" onclick="submit()"/>
</form>
</body>
</html>
回答1:
Because submit() is the reserved function to submit a form in core JS.
For example, if your form had an id like myform, you could do this to submit it via JS:
document.form['myform'].submit();
So calling that function you're actually submitting the form and not calling your custom function.
EDIT: I forgot to mention, it only works inside the form because it's calling the submit function of that form. Out of it it's not available anymore (since the body tag doesn't have a submit function).
回答2:
Form elements are placed on the scope chain of listeners within the form as if by:
with (form) {
/* run listener code */
}
so the identifier submit is first resolved in the context of the handler, then on the form before the rest of the scope chain. This is unique to forms and can be seen in the following:
<form>
<input name="foo">
<input type="button" value="Do click" onclick="
function submit(){console.log('click')};
submit();
">
</form>
where clicking the button runs the submit function within listener, and removing the function declaration runs the form's submit method. This is unique to forms.
Note that when a form's submit method is called directly, its submit handler is not called.
Outside of the form, the identifier submit is resolved in the normal way.
来源:https://stackoverflow.com/questions/25222715/javascript-form-onsubmit-does-not-work-when-function-is-called-submit