I am having trouble populating a ul li with its index value.
My HTML below.
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
My JS below.
$('document').ready(function(){
var indexus = $('li').index();
$('li').each(function(){
$('li').html(indexus);
});
});
JS Fiddle: http://jsfiddle.net/kuJWc/407/
I want to populate the li
with its appropriate li
index value, but I can only end up getting the index value of the latest (in this case 3). How would I go about looping in each index value so that each li
shows the value of its own index number?
you should do like this:
$('li').each(function(){
$(this).html($(this).index());
});
you were adding the index to all the li
.. so istead of $(this)
inside of the each, you were using $('li').
which adds the last value li index to all of them.
Try this:
$('document').ready(function(){
$('li').each(function(){ // iterate through each `li`
var $li = $(this); // get the current `li` element
var index = $li.index(); // get the current `li` index
$li.html(index); // set the `li`'s html to the index value
});
});
I added some comments to help you understand what each step does, I hope that helps!
What about this:
$('document').ready(function(){
var indexus = $('li');
for (var i = 0; i <= indexus.length; i++) {
$(indexus[i]).html(i);
}
});
Here it works.
You can get an array of the ul's children and then iterate over each of the children with something like this:
var arr = $('ul').children();
for (var i = 0; i < arr.length; i++){
$(arr[i]).html(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.