我有一个 ASP.NET 代码隐藏页面,将多个复选框链接到 JavaScript 方法。我只想创建一个 JavaScript 方法来处理所有这些,因为它们是相同的逻辑,我该怎么做?
页面加载后的代码:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX 页面 JavaScript;显然,他们都对分配的复选框执行相同的操作,但我认为这可以简化为一种方法:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
最佳答案
将引发事件的复选框添加到事件中:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
然后在函数中声明它,如下所示:
function checkBoxShowPrices_click(checkbox, e){ ...}
并且您在复选框中有您需要的实例
关于asp.net - 如何将相似的 JavaScript 方法组合成一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808310/