[英]e.preventDefault() is not working for submit button and anchor tag in MVC
在我的ASP.Net核心MVC应用程序中
视图
<form>
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-4">
<div class="form-group">
<input type="text" class="form-control small" asp-for="UserName" />
</div>
<div class="form-group">
<input type="text" class="form-control small" asp-for="Password" />
</div>
<div class="form-group">
<a class="btn btn-sm btn-success pull-right" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin()">Log In</a>
<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />
</div>
</div>
</div>
</div>
TypeScript代码
function ValidateLogin(e:Event) {
var username = (document.getElementById('UserName') as HTMLInputElement).value;
var password = (document.getElementById('UserName') as HTMLInputElement).value;
if ((username.length > 0) && (password.length > 0)) {
}
else {
alert('Fields required');
e.preventDefault();
}
}
如果字段为空,则应终止请求,但它只显示alert和e,preventDefault()在这里无效。
我也试过返回false,但似乎没有什么工作在这里。 它不应该在preventDefault之后转到action方法或返回false语句
在这个非常简单的任务中,有人可以告诉我这里缺少什么吗?
更新1
如果我以下面的方式更改代码,那么它的工作原理
document.getElementById('btn').onclick = function (e) {
var username = (document.getElementById('UserName') as HTMLInputElement).value;
var password = (document.getElementById('UserName') as HTMLInputElement).value;
if ((username.length > 0) && (password.length > 0)) {
}
else {
alert('Fields required');
return false;
}
}
我仍然不知道为什么它在我用方法包装而不是直接用.onclick()调用时不起作用
onclick="ValidateLogin(this)"
您的问题是您的ValidateLogin方法。 您传递“this”上下文,您的方法需要一个事件参数。
这样做。
<form onsubmit="ValidateLogin()">
从提交按钮中删除onlclick
。
我也试过返回false,但似乎没有什么工作在这里。 它不应该在preventDefault之后转到action方法或返回false语句
正如kemicofa的回答所指出的那样,您的ValidateLogin
函数需要将Event
作为参数。 但你通过了this
。
我们来检查你的代码:
<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />
这里的ValidateLogin(this)
表示您告诉浏览器将此input
DOM元素作为参数传递给ValidateLogin()
函数。 由于Input
元素没有preventDefault
方法,因此失败。
我仍然不知道为什么它在我用方法包装而不是直接用
.onclick()
调用时.onclick()
总之,这里的this
引用的DOM元素这是我们重视的事件处理程序之一 。 无论如何, this
不是Event
的实例。
如果您更喜欢使用on{eventtype}="script_code"
HTML属性绑定事件处理程序,则可以使用event
变量:
onclick="ValidateLogin(this)"onclick="ValidateLogin(event)"
因为event
可以被视为script_code
的预定义局部变量。 有关更多详细信息,请参阅注册事件处理程序
通过设置.onclick=function(event){/**/};
调用.onclick=function(event){/**/};
从JavaScript和调用带有内联HTML属性的ValidateLogin(event)
应该按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.