[英]Populating ul list with index
I am having trouble populating a ul li with its index value. 我在用其索引值填充ul时遇到问题。
My HTML below. 我的HTML在下面。
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
My JS below. 我的JS在下面。
$('document').ready(function(){
var indexus = $('li').index();
$('li').each(function(){
$('li').html(indexus);
});
});
JS Fiddle: http://jsfiddle.net/kuJWc/407/ JS小提琴: 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). 我想用适当的
li
索引值填充li
,但最终只能获取最新的索引值(在本例中为3)。 How would I go about looping in each index value so that each li
shows the value of its own index number? 我将如何循环每个索引值,以便每个
li
显示其自身索引号的值?
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').
您将索引添加到所有
li
..因此,您使用的是$('li').
,而不是每个li
里面的$(this)
$('li').
which adds the last value li index to all of them. 这会将最后一个值li索引添加到所有这些索引中。
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! 我添加了一些评论以帮助您了解每个步骤的作用,希望对您有所帮助!
You can get an array of the ul's children and then iterate over each of the children with something like this: 您可以获取ul的孩子的数组,然后使用以下方法遍历每个孩子:
var arr = $('ul').children();
for (var i = 0; i < arr.length; i++){
$(arr[i]).html(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.