How can I give li the value of a,b,c? currently with my below code I got all c.
arr = ['a','b','c'];
arr.forEach(function(obj){
var x = obj;
$('li').each(function () {
$(this).text(x);
});
});
Something is wrong with my code?
First, you set the text of all li to 'a', then to 'b' and finally to 'c'.
Instead, you may try iterating the li elements, and set the text content of the current one to the corresponding item in arr:
var arr = ['a','b','c'];
$('li').each(function(i) {
$(this).text(arr[i]);
});
var arr = ['a','b','c'];
$('li').each(function(i) {
$(this).text(arr[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
Alternatively (but similarly), you can iterate the array, and set the text content of the corresponding li to the current value:
var arr = ['a','b','c'],
$li = $('li');
arr.forEach(function(txt, i) {
$li.eq(i).text(txt);
});
var arr = ['a','b','c'],
$li = $('li');
arr.forEach(function(txt, i) {
$li.eq(i).text(txt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
That is because you are iterating over all li when iterating over array and setting the value. jquery .text() accepts function as argument which accepts index as parameter. This will eliminates the need of iterating over li and array elements:
var arr = ['a','b','c'];
$('li').text(function(i){
return arr[i];
});