2013-05-10 52 views
1

在JavaScript中連接字符串的正確方法是什麼?例如,我有這個:編寫字符串連接的正確方法

var addmore ='<tr>'+'<td style="text-align: center">'+currentIndex+'</td>'+'<td id="small"><input style="background: white; color: black;" type="text" id="number_'+currentIndex+'" value="">'+'</td><td><input style="background: white; color: black;" type="text" id="label_'+currentIndex'"></td></tr>' 

它在this fiddle顯示一個錯誤,但我找不到它。我檢查了引號,他們似乎是正確的。

引號太多會導致JavaScript中的混淆和錯誤?或者必須"超出'

+0

語法突出顯示有時很有用。滾動瀏覽並查看事情的不同之處。 – alex 2013-05-10 07:41:04

+4

'id =「label _'+ currentIndex'」'缺少'+'。 – Ohgodwhy 2013-05-10 07:41:27

+0

哦,我的!謝謝! – yvonnezoe 2013-05-10 07:43:39

回答

4

一個更好,更整潔WA y要這樣做:

var addmore ='<tr>'+ 
      '<td style="text-align: center">'+currentIndex+'</td>'+       
      '<td id="small"><input style="background: white; color: black;" type="text" id="number_'+currentIndex+'" value=""></td>'+ 
      '<td><input style="background: white; color: black;" type="text" id="label_'+currentIndex+'"></td>'+ 
      '</tr>'; 
0

適當的這樣的

var addmore ='<tr><td style="text-align: center">'+currentIndex+'</td><td id="small"><input style="background: white; color: black;" type="text" id="number_'+currentIndex+'" value=""></td><td><input style="background: white; color: black;" type="text" id="label_'+currentIndex+'"></td></tr>'; 
+0

爲什麼downvote .. ??任何理由 – Gautam3164 2013-05-10 07:42:55

+0

它不是我投票你。讓我給你投票! ;) – yvonnezoe 2013-05-10 07:44:19

0

試試這個:

var addmore = '<tr><td style="text-align: center">' + currentIndex + '</td><td id="small"><input style="background: white; color: black;" type="text" id="number_' 
       + currentIndex + '" value="">' + '</td><td><input style="background: white; color: black;" type="text" id="label_' + currentIndex + '"></td></tr>'; 
+1

謝謝你,upvote! – yvonnezoe 2013-05-10 07:44:38

1

對於字符串concatination我傾向於在Python中使用字符串格式等。在該項目中使用的所有網頁中common.js文件中的代碼頂部定義字符串格式

試試這個(http://jsfiddle.net/9Xw8Q/1/

if (!String.prototype.format) { 
    String.prototype.format = function() { 
     var args = arguments; 
     return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined' 
       ? args[number] 
       : match 
       ; 
     }); 
    }; 
} 

,然後使用它像這樣

currentIndex = 20 

var addmore ='<tr><td style="text-align: center">{0}</td><td id="small"><input style="background: white; color: black;" type="text" id="number_{0}" value=""></td><td><input style="background: white; color: black;" type="text" id="label_{0}"></td></tr>'.format(currentIndex) 
+1

謝謝您分享知識!這可以是我未來的參考。 +1 – yvonnezoe 2013-05-10 08:01:18

1

你可以在這裏看到的輸出:http://jsbin.com/abiduw/1/edit

currentIndex=5; 
var addMore = '<tr><td style="text-align: center">'+currentIndex+'</td><td id="small"><input style="background: white; color: black;" type="text" id="number_'+currentIndex+'" value=""></td><td><input style="background: white; color: black;" type="text" id="label_'+currentIndex+'"></td></tr>'; 
+0

感謝您介紹jsbin! +1 – yvonnezoe 2013-05-10 08:08:59