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>'

它在这个小提琴中显示一个错误,但我找不到它。我检查了引号,它们似乎是正确的。

过多的引号会导致 JavaScript 中的混乱和错误吗?还是必须"在外面'

4

5 回答 5

4

一种更好更整洁的方法:

 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>';
于 2013-05-10T07:54:40.287 回答
1

对于字符串连接,我倾向于使用 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)
于 2013-05-10T07:52:59.700 回答
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>';
于 2013-05-10T07:54:05.760 回答
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>';
于 2013-05-10T07:41:03.993 回答
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>';
于 2013-05-10T07:41:12.040 回答