[英]How to combine similar JavaScript methods to one
我有一個 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){ ...}
並且您在復選框中有您需要的實例
您始終可以編寫一個返回函數的函數:
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);
我想這可能對你的情況有所幫助。 (您的代碼粘貼很難閱讀..)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.