gpt4 book ai didi

javascript - 从客户端处理程序返回 false 不会阻止回发

转载 作者:行者123 更新时间:2023-11-30 12:55:57 25 4
gpt4 key购买 nike

我在 WebForms 页面上有以下按钮:

<asp:Button ID="btnNewProgramNext" runat="server" Text="Next &gt;&gt;" />

我有以下 javascript/jquery 来处理它的事件。

$('#<%= btnNewProgramNext.ClientID %>').on('click', function (e) {
var errorMessage = '';
var ok = false;
var newCompany = $('#<%= NewCompanyMode.ClientID %>').val();
if (newCompany == 1) {
if (!$('#<%= txtProgramCompanyName.ClientID %>').val())
errorMessage = 'You must enter a company name.';
else if (!$('#<%= txtContactFirstName.ClientID %>').val())
errorMessage = 'You must enter a contact first name.';
else if (!$('#<%= txtContactLastName.ClientID %>').val())
errorMessage = 'You must enter a contact last name.';
else
ok = true;
}
else {
// Do something else
ok = true;
}
$('#newProgramErrorMessage').text(errorMessage);
return ok;
});

问题是,当此处理程序返回 false 时(当 ok 为 false 时,或者当我将最后一行更改为 return false 时),回发仍然发生。

有什么技巧可以防止 javascript 回发吗?我希望这能奏效。

最佳答案

你需要 e.preventDefault() 来取消按钮点击事件。

$('#<%= btnNewProgramNext.ClientID %>').on('click', function (e) {
var errorMessage = '';
var ok = false;
var newCompany = $('#<%= NewCompanyMode.ClientID %>').val();
if (newCompany == 1) {
if ($('#<%= txtProgramCompanyName.ClientID %>').val() == "")
errorMessage = 'You must enter a company name.';
else if ($('#<%= txtContactFirstName.ClientID %>').val() == "")
errorMessage = 'You must enter a contact first name.';
else if ($('#<%= txtContactLastName.ClientID %>').val() == "")
errorMessage = 'You must enter a contact last name.';
else
ok = true;
} else {
// Do something else
ok = true;
}
if (!ok) {
e.preventDefault();
$('#newProgramErrorMessage').text(errorMessage);
}
// else everything is valid, so post back to server.
});

关于javascript - 从客户端处理程序返回 false 不会阻止回发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19121140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com