javascript onsubmit无法正常工作

我试图让 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>

FIDDLE

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面