[英]Javascript combine 2 functions into one
我對此也有類似的問題:將3個函數合並為javascript中的一個
我有功能:
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
..是否有可能使一個功能,並與選擇另一種價值觀打電話了嗎? 提前致謝
在您的測試函數中使用一個param,然后用該param替換所有test
實例(當作為屬性訪問時,例如columns.test
,請使用方括號表示法評估該param)
test: function(selectorValues) {
for (var i = 0; i < settings.columns[selectorValues].length; i++) {
$table.find('tbody td' + selectorValues).each(function() {
$.each(jQuery.parseJSON(settings.columns[selectorValues][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...
});
});
}
},
//invoke using the objects you created (or pass values directly)
test(columns.test1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.