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