我有類似的問題與此:Combine 3 functions into one in javascript的Javascript結合2種功能於一體
我具備的功能:
test: function() {
for (var i = 0; i < settings.columns.test.length; i++) {
$table.find('tbody td.test').each(function() {
$.each(jQuery.parseJSON(settings.columns.test[i][1]), function(index, value) {
if ($(this).text() === value) {
input += '<option value="' + index + '" selected>' + value + '</option>';
} else {
input += '<option value="' + index + '">' + value + '</option>';
}
//more code...
});
});
}
},
test2: function() {
for (var i = 0; i < settings.columns.test2.length; i++) {
$table.find('tbody td.test2').each(function() {
$.each(jQuery.parseJSON(settings.columns.test2[i][1]), function(index, value) {
if ($(this).text() === value) {
input += '<option value="' + index + '" selected>' + value + '</option>';
} else {
input += '<option value="' + index + '">' + value + '</option>';
}
//more code...
});
});
}
},
我通過調用這些函數:
columns: {
test1: [["key", '{"0": "First value", "1": "Second Value"}']],
test2: [["key", '{"0": "One more value", "1": "One more more value"}']]
}
正如你看到的,這兩個函數是相同的,只有test
- >test2
..是否有可能創建一個函數並使用其他值作爲選擇器調用它?在此先感謝
對於簡單東西,使用params很好。但是,如果出於任何原因想要有2個函數test1&test2,則可以使用函數閉包來創建它們。不知道正確的詞是什麼,但功能的建設者會聽起來正確.. – Keith
提取可變的東西作爲函數的參數,如'function(selector,column)' –