2016-01-22 139 views
0
for (i = 0; i < arrayData.length; i++) { 
     $(".swipe-wrap").append("<div class=\"final\">Hello!</div>"); 
     console.log('hello'); 
    } 

这是我目前拥有的。我的arrayData是改变每个负载的数组。在循环内Javascript增量

我怎样才能得到它,所以我的班final每个for循环将有一个像这样的计数器:<div class="final_1">Hello!</div><div class="final_2">Hello!</div> ..

+3

的HTML是只是一个字符串,你知道...'$(...)追加( '

' + i + '
');' –

+0

@MarcB猜测一直在我的代码我的头太长哈哈。现在你指出这很明显,很抱歉浪费你的时间。谢谢您的帮助! – PourMeSomeCode

+0

你为什么要枚举类?我很自信,你试图用这个问题来解决另一个问题。 – Thomas

回答

3
for (i = 0; i < arrayData.length; i++) { 
    $(".swipe-wrap").append("<div class=\"final_"+i+"\">Hello!</div>"); 
    console.log('hello'); 
} 
+0

啊人,应该看到。谢谢您的帮助! – PourMeSomeCode

0

内循环,则不应进行DOM操作。始终执行批量操作。

试试这个:

var html = "" 
for (i = 0; i < arrayData.length; i++) { 
    html += '<div class="final_'+i+'">Hello!</div>'; 
    console.log('hello'); 
} 
$(".swipe-wrap").append(html); 

您还可以使用Array.forEach。 。

var html = "" 
 
var arrayData = ["test1", "test2", "test3", "test4", "test5"]; 
 
console.log(arrayData); 
 
arrayData.forEach(function(item, index) { 
 
    html += '<div class="tile final_' + index + '">Hello ' +item+ '!</div>'; 
 
    console.log('hello'); 
 
}); 
 
$(".swipe-wrap").append(html);
.swipe-wrap { 
 
    background: #eee; 
 
    padding: 10px; 
 
    border: 1px solid gray; 
 
} 
 
.tile { 
 
    width: auto; 
 
    padding: 10px; 
 
    margin: 10px; 
 
    background: #fff; 
 
    border: 1px solid #ddd; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div class="swipe-wrap"></div>