0

我正在寻找一种简洁的方法来编码以下示例中的 append 参数:

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'></div><div class='cellGrip cellGrip_sw' title='Drag'></div><div class='cellGrip cellGrip_ne' title='Drag'></div><div class='cellGrip cellGrip_nw' title='Drag'></div>");

以上工作,但为了清楚起见,我宁愿写:

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'></div>
                <div class='cellGrip cellGrip_sw' title='Drag'></div>
                <div class='cellGrip cellGrip_ne' title='Drag'></div>
                <div class='cellGrip cellGrip_nw' title='Drag'></div>");

但后来我收到有关未终止字符串的投诉。

感谢您的任何想法。

4

4 回答 4

2

你可以这样做...

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'></div>" +
               "<div class='cellGrip cellGrip_sw' title='Drag'></div>" +
               "<div class='cellGrip cellGrip_ne' title='Drag'></div>" +
               "<div class='cellGrip cellGrip_nw' title='Drag'></div>");

或这个...

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'></div>\
                <div class='cellGrip cellGrip_sw' title='Drag'></div>\
                <div class='cellGrip cellGrip_ne' title='Drag'></div>\
                <div class='cellGrip cellGrip_nw' title='Drag'></div>");

但第二个将在每行的开头插入所有空格。

于 2013-10-01T22:04:14.327 回答
1

您可以转义文字换行符

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'></div> \
                <div class='cellGrip cellGrip_sw' title='Drag'></div> \
                <div class='cellGrip cellGrip_ne' title='Drag'></div> \
                <div class='cellGrip cellGrip_nw' title='Drag'></div>");

就个人而言,我更愿意这样做:

var arr  = ['se', 'sw', 'ne', 'nw'],
    frag = document.createDocumentFragment();

$.each(arr, function(_, key) {
    var div = $('<div />', {'class':'cellGrip cellGrip_'+key, title: 'Drag'});
    $(frag).append(div);
});

imgBox$.append(frag);
于 2013-10-01T22:04:46.457 回答
1

只需添加一个\.

imgBox$.append("<div class='cellGrip cellGrip_se' title='Drag'>a</div> \
                <div class='cellGrip cellGrip_sw' title='Drag'>b</div> \
                <div class='cellGrip cellGrip_ne' title='Drag'>c</div> \
                <div class='cellGrip cellGrip_nw' title='Drag'>d</div>");
于 2013-10-01T22:04:55.043 回答
1

您可以迭代以构建字符串,然后附加它

var dir = ["se","sw","ne","nw"];
var divs = "";
for( var i = 0; i < 4; i++ ){
 divs += "<div class='cellGrip cellGrip_"+dir[i]+"' title='Drag'></div>";
}
imgBox$.append(divs);
于 2013-10-01T22:07:05.410 回答