[英]map array to elements text using jQuery.each inside a for loop?
for the given html: 对于给定的html:
<div id="parent">
<div class="child">x</div>
<div class="child">y</div>
<div class="child">z</div>
</div>
How can I map the text of its children from an array? 如何从数组映射其子级文本?
This is my try: 这是我的尝试:
var myArray = ['a', 'b', 'c'];
for (var i = -1; i < myArray.length; i++) {
$('#parent .child').each(function () {
$(this).text(myArray[i]);
});
}
I get: c,c,c
我得到:
c,c,c
How can I get a,b,c
? 我如何获得
a,b,c
?
You don't need the outer for
loop: 您不需要外部的
for
循环:
var myArray = ['a', 'b', 'c'];
$('#parent .child').each(function (index) {
$(this).text(myArray[index]);
});
There's no need to use for
loop here. 此处无需使用
for
循环。
var myArray = ['a', 'b', 'c']; $('#parent').find('div').each(function(){ $(this).html(myArray[$(this).index()]); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> <div class="child">x</div> <div class="child">y</div> <div class="child">z</div> </div>
Use .text(function)
使用
.text(function)
var myArray = ['a', 'b', 'c']; $("#parent > .child").text(function(index) { return myArray[index] })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div id="parent"> <div class="child">x</div> <div class="child">y</div> <div class="child">z</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.