我有以下内容:
function grid() {
console.log("Grid loaded");
var gridHtml = "";
for (var i = 1; i < gridSize + 1; i++) {
gridHtml += '<div data-value="var i" class="grid pointer">' + i + "</div>";
$("#gridContainer").append(gridHtml); //append
}
}
所以我将VARIABLE i附加到文档中, 如何使变量I的内容(在这种情况下它是一个数字)出现在数据属性标记中?
基本上,我希望它像<div data-value="1" class="grid pointer"></div>
<div data-value="2" class="grid pointer"></div>
<div data-value="3" class="grid pointer"></div>
<div data-value="4" class="grid pointer"></div>
提前感谢。
答案 0 :(得分:0)
使用字符串连接将值变量i
连接到字符串leteral,也不需要字符串+=
,因为您要在循环中附加字符串
function grid() {
console.log("Grid loaded");
var gridHtml = "";
for (var i = 1; i < gridSize + 1; i++) {
gridHtml = '<div data-value="' + i + '" class="grid pointer">' + i + "</div>";
$("#gridContainer").append(gridHtml); //append
}
}
演示:Fiddle
另一个选项是连接所有循环字符串,然后在循环完成后将其附加到容器
function grid() {
console.log("Grid loaded");
var gridHtml = "";
for (var i = 1; i < gridSize + 1; i++) {
gridHtml += '<div data-value="' + i + '" class="grid pointer">' + i + "</div>";
}
$("#gridContainer").append(gridHtml); //append
}
演示:Fiddle
答案 1 :(得分:0)
尝试
for (var i = 1; i < gridSize+1;i++) {
gridHtml += '<div data-value="'+ i +'" class="grid pointer">' +i+ '</div>';
$("#gridContainer").append(gridHtml); //append
}
答案 2 :(得分:0)
gridHtml += '<div data-value='+i+' class="grid pointer">' +i+"</div>";
这样做