我正在寻找一种干净的方法来编写下面示例中的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>");
但后来我接到关于未终结字符串的投诉。
感谢任何想法。
答案 0 :(得分: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>");
但第二个将在每行的开头插入所有空格。
答案 1 :(得分: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);
答案 2 :(得分: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>");
答案 3 :(得分: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);