这样我就可以更好地理解如何编写 PreventDefault 而不是 return false。这是返回 false 的示例。我想使用 PreventDefault 重写此代码
我的 HTML:
<form name="myForm" action="formPracticePHP.php" method="post" onsubmit="return validateForm()">
<p>Enter your Name: <input type="text" name="name" value="" placeholder="[your-name]" required="required" /><br /></p>
<p>Enter your Age: <input type="number" name="age" size="6" value="" /><br /></p>
<p>Please Select Your Favorite Fruit</p>
<select name="fruit" id="fruit">
<option value="nothing" selected="selected">Select A Fruit</option>
<option value="Bannana">Bannana</option>
<option value="Kiwi">Kiwi</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Cherry">Cherry</option>
</select>
<input type="submit" name="submit" value="submit" id="submitBtn" />
</form>
我的 JavaScript
function validateForm() {
var x = document.forms["myForm"]["age"].value;
var x2 = document.forms["myForm"]["fruit"].value;
if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
alert("Age and fruit selection must be filled out");
return false;
}
}
最佳答案
您必须将事件
参数传递给您的处理程序
<form onsubmit="validateForm(event)" >
并改变你的功能
function validateForm(e) {
var x = document.forms["myForm"]["age"].value;
var x2 = document.forms["myForm"]["fruit"].value;
if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
e.preventDefault();
alert("Age and fruit selection must be filled out");
}
}
如果您从 JavaScript 设置处理程序,上面的相同函数也将起作用。
关于javascript - 如何使用preventDefault重写而不是return false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27650834/