2011-10-13 66 views
3

我有如下腳本: 我想包含如下所示的索引值。我怎樣才能做到這一點?用我的實際代碼,我有錯誤如何在JavaScript字符串中包含變量

for(var index = 1; index < 6; index++){ 

    $("#myTable thead td:nth-child(index + 2).html("here"); 

} 
+0

你的例子缺少一個括號。你確定你的代碼? –

+0

你的代碼不起作用,因爲你缺少一個關閉括號,原因有一個...... @Curt有正確的答案 – musefan

+0

你的語法缺少一個靜物,但我想你可以在html函數中做到這一點:html(var + 「
」)? –

回答

0

你可以這樣做:

for(var index = 1; index < 6; index++){ 
    var nthchild = index+2; 
    $("#myTable thead td:nth-child("+nthchild+")").html(index); 
} 
+0

+1,因爲我看不到投票的理由。 –

+0

@Ash Burlaczenko我認爲它得到了編輯(不是我downvoted) – Curt

0

字符串連接,並整理你的語法錯誤:

for(var index = 1; index < 6; index++) 
    {  
     $("#myTable thead td:nth-child(" + (index+2) + ")").html('here'); 
    } 
0

你必須寫:

for(var index = 1; index < 6; index++) { 
    $("#myTable thead td:nth-child("+(index+2)+")").html("here"); 
} 
相關問題