我正在尝试使 javascript 函数在提交表单时起作用,但该函数似乎没有运行。谁能帮忙?
<html>
<head>
<script>
function upload(){
alert("I am an alert box!");
}
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post" onsubmit="return upload();">
<input type="file" name="file">
<input type="submit" name="upload" value="Datei hochladen">
</form>
</body>
</html>
最佳答案
将事件处理程序附加到表单元素时,事件处理程序的范围是表单而不是窗口
<form enctype="multipart/form-data" method="post" onsubmit="return upload(this);">
<script>
function upload(scope) {
console.log(scope); // The passed scope from the event handler is
} // the form, and not window
</script>
由于表单中的输入元素作为属性附加到表单对象,其中名称是键,在事件处理程序中调用 upload()
,其中范围是表单,将等于调用 form.upload()
,但是表单已经有一个同名的元素,所以 form.upload
是上传按钮,而不是 upload()
在全局范围内运行。
要解决这个问题,要么重命名函数,要么重命名元素
<html>
<head>
<script>
function upload(){
alert("I am an alert box!");
}
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post" onsubmit="return upload();">
<input type="file" name="file">
<input type="submit" name="upload2" value="Datei hochladen">
</form>
</body>
</html>
关于javascript onsubmit 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581273/