e.preventDefault()不工作在MVC提交按钮和锚标记

问题描述 投票:1回答:2

在我的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>

打字稿代码

   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();
    }
}

如果字段为空比它应该终止该请求,但它只显示警报和E,preventDefault()方法是无效的在这里。

我也试过返回false,但似乎没有在这里工作。它不应该去操作方法的preventDefault后或返回虚假陈述

谁能告诉我,我在这里缺少在这个非常简单的任务是什么?

更新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调用的不工作()

javascript typescript asp.net-core-mvc
2个回答
1
投票

我也试过返回false,但似乎没有在这里工作。它不应该去操作方法的preventDefault后或返回虚假陈述

作为qazxsw POI指出,您的qazxsw POI功能期待一个qazxsw POI作为参数。但你通过了kemicofa's answer

让我们来检查你的代码:

ValidateLogin

在这里,Event意味着你告诉浏览器通过这个this DOM元素<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" /> function作为参数。作为ValidateLogin(this)元素没有input方法,它失败。

不过我不知道为什么,当我的方法把它包不能正常工作,而不是直接与ValidateLogin()调用

总之,这里的Input引用的DOM元素这是我们重视的事件处理程序之一。无论如何,preventDefault不是.onclick()的实例。

如果你喜欢与this HTML属性绑定的事件处理程序,您可以使用this变量:

    onclick="ValidateLogin(this)"

    onclick="ValidateLogin(event)"

因为Event可能被视为为您on{eventtype}="script_code"预先定义的局部变量。有关详细信息,请参阅event

这两个调用通过从JavaScript设置event和调用script_code用内嵌HTML属性应该正常工作。


2
投票
Registering on-event handlers

你的问题是你ValidateLogin方法。你通过“本”方面,你的方法需要一个事件参数。

做到这一点,而不是。

.onclick=function(event){/**/};

从您的提交按钮ValidateLogin(event)

© www.soinside.com 2019 - 2024. All rights reserved.