此代码不起作用:
<form name="keeper" action="
javascript:if(this.value='')
{alert('password empty');};
else{location.href = window.document.keeper.page.value + '.php';}"
style="margin:2vh;">
<div style="display:inline;">
<input type="text" name="page">
<input type="submit" value="Go">
<noscript>
<div style="display:inline;color:#ff0000; background-color:#ffff66;
font:normal 11px tahoma,sans-serif;">
<br> Javascript is required to access this<br>area. Yours seems to be disabled.
</div>
</noscript>
</div>
</form>
如果文本框为空,当提交表单时,我想alert("密码为空")
。如果不是这样,我希望脚本在当前页面中加载 window.document.keeper.page.value + '.php'
。
最佳答案
该内联 action
block 非常不可读,不推荐。有更好的方法可以做到这一点,并且更符合标准。请执行以下操作:
document.querySelector("form[name=keeper]").addEventListener("submit", function(e){
var input = document.querySelector("input[name=page]");
//e refers to the event - submit
if (input.value == '')
{
alert("password empty");
}
else
{
location.href = input.value + '.php';
}
e.preventDefault(); //this will cancel the normal submit and execute the code above.
return false;
})
<form name="keeper" style="margin:2vh;">
<div style="display:inline;">
<input type="text" name="page">
<input type="submit" value="Go">
<noscript>
<div style="display:inline;color:#ff0000; background-color:#ffff66; font:normal 11px tahoma,sans-serif;"> <br>Javascript is required to access this<br>area. Yours seems to be disabled.</div>
</noscript>
</div>
</form>
关于JavaScript 验证和重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46910091/