2017-08-24 66 views
0

我有類似的問題與此: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 ..是否有可能創建一個函數並使用其他值作爲選擇器調用它?在此先感謝

+0

對於簡單東西,使用params很好。但是,如果出於任何原因想要有2個函數test1&test2,則可以使用函數閉包來創建它們。不知道正確的詞是什麼,但功能的建設者會聽起來正確.. – Keith

+0

提取可變的東西作爲函數的參數,如'function(selector,column)' –

回答

3

在您的測試function使用PARAM,然後用param所取代的test所有實例(如屬性訪問時,如columns.test,使用bracket notation來評估,而不是帕拉姆)

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) 
+0

請注意,jQuery啓用[多選擇器](https:/ /api.jquery.com/multiple-selector/)查詢元素時。所以'$ table.find('tbody td.test,tbody td.test2')'應該是一個有效的選擇器,可能很容易解決OP的問題。 –

+0

好的,非常感謝你,但是我現在怎麼使用這個功能呢?我的代碼:'$(「#profileTable」)。Tabledit {{0,「id」], row:[[ 「]], test2:[['value ....']] } });' – EvaldasL

+0

我使用的是http://markcell.github.io/jquery-tabledit/,我需要先編寫'Draw.columns.test1(); Draw.columns.test2();' – EvaldasL