Asp.net 如何将类似的JavaScript方法组合为一个

Asp.net 如何将类似的JavaScript方法组合为一个,asp.net,javascript,Asp.net,Javascript,我有一个ASP.NET代码隐藏页面,将几个复选框链接到JavaScript方法。我只想用一个JavaScript方法来处理它们,因为它们是相同的逻辑,我该怎么做呢 代码隐藏页面加载: checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);"); checkBoxShowInventory.Attributes.Add("oncli

我有一个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)%>");
        }
    }
功能复选框showPrices\u单击(e){
如果(_已更改){
证实(
'所有更改都将丢失。是否继续?',
函数(arg){
如果(arg.toUpperCase()==“是”){
var checkBox=document.getElementById(“”);
checkBox.checked=!checkBox.checked;
eval(“”);
_hasChanged=false;
}
});
返回false;
}否则{
eval(“”);
}
}
功能复选框ShowInventory\u单击(e){
如果(_已更改){
证实(
'所有更改都将丢失。是否继续?',
函数(arg){
如果(arg.toUpperCase()==“是”){
var checkBox=document.getElementById(“”);
checkBox.checked=!checkBox.checked;
eval(“”);
_hasChanged=false;
}
});
返回false;
}否则{
eval(“”);
}
}

您始终可以编写返回函数的函数:

function genF(x, y) {
    return function(z) { return x+y*z; };
};

var f1 = genF(1,2);
var f2 = genF(2,3);

f1(5);
f2(5);

我想这对你可能会有帮助。(您的代码粘贴很难阅读。)

将引发该事件的复选框添加到事件中:

checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
然后在函数中声明如下:

function checkBoxShowPrices_click(checkbox, e){ ...}

您在所需的实例中选中了复选框

,是否可以将代码编辑得不那么新颖?