如何将类似的javascript方法组合成一个

时间:2009-04-30 18:11:21

标签: asp.net javascript

我有一个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)%>");

    }

}

2 个答案:

答案 0 :(得分:2)

向该事件添加提升它的复选框:

checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");

之后在函数中你声明它是这样的:

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

你在复选框中有你需要的实例

答案 1 :(得分:0)

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

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

我认为这可能会对你的情况有所帮助。 (您的代码粘贴难以阅读..)

相关问题