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?
3 个解决方案
#1
4
You don't need the outer for
loop:
你不需要外部for循环:
var myArray = ['a', 'b', 'c'];
$('#parent .child').each(function (index) {
$(this).text(myArray[index]);
});
#2
2
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>
#3
2
Use .text(function)
使用.text(函数)
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>
#1
4
You don't need the outer for
loop:
你不需要外部for循环:
var myArray = ['a', 'b', 'c'];
$('#parent .child').each(function (index) {
$(this).text(myArray[index]);
});
#2
2
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>
#3
2
Use .text(function)
使用.text(函数)
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>