Mav*_*ick 1 arrays jquery for-loop append
可以说divs我的HTML中有三个
<div>
<h2>This is div 1</h2>
</div>
<div>
<h2>This is div 2</h2>
</div>
<div>
<h2>This is div 3</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
另外,我有一个由三个嵌套数组组成的JavaScript数组:
var array = [
[ "<p>Bla bla</p>", "<p>Other stuff</p>"],
[ "<p>Another paragraph</p>"],
[ "<p>Yet another</p>", "<p>yes</p>", "<p>yes</p>" ]
];
Run Code Online (Sandbox Code Playgroud)
我确信这个数组总是有三个成员,就像数量一样divs.
我想要做的是将主数组的每个嵌套数组的内容附加到具有相应数字的div.
就像是:
for ( var i = 0; i < array.length; i++ ) {
$('div').eq( i ).append( array[i] );
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,但我认为我的意图很明确.
你可以在这里找到一个有效的例子=> http://jsfiddle.net/G8BsK/
谢谢.
小智 5
改变这个......
.append( array[i] );
Run Code Online (Sandbox Code Playgroud)
对...
.append( array[i].join('') );
Run Code Online (Sandbox Code Playgroud)
虽然我强烈建议将DOM选择从循环中取出并缓存它.
var divs = $('div');
for ( var i = 0; i < array.length; i++ ) {
divs.eq( i ).append( array[i].join('') );
}
Run Code Online (Sandbox Code Playgroud)
......或者只是这样做......
$('div').append(function(i) {
return array[i].join('');
});
Run Code Online (Sandbox Code Playgroud)