jQuery: Add Numbers into an Ordered List
I would like to use jQuery to make this:
<ol>
<li>item a</li>
<li>item b</li>
</ol>
<ol>
<li>item c</li>
<li>item d</li>
<li>item e</li>
</ol>
…become this:
<ol>
<li><span>1</span> item a</li>
<li><span>2</span> item b</li>
</ol>
<ol>
<li><span>1</span> item c</li>
<li><span>2</span> item d</li>
<li><span>3</span> item e</li>
</ol>
(This answer doesn't work for when there are multiple ol
s on the page; the number would increment across the ol
s instead of starting from 1 for each开发者_JAVA技巧 individual ol
.)
Or like this:
$('ol > li').each(function() {
$(this).prepend("<span>" + ($(this).index() +1) + "</span>");
});
Reference: prepend()
, index()
You could do something like this (since jQuery 1.4+, .prepend()
takes a function):
$("ol").each(function() {
$("li", this).prepend(function(i) {
return $("<span />", {text: i+ 1 });
});
});
You can see a working demo here
Or, even shorter, but less efficient:
$("ol li").prepend(function() {
return $("<span />", {text: $(this).index() +1 });
});
You can see that demo here
Probably not the best solution, but it gets the job done :
$('ol').each(function() {
$(this).children('li').each(function(i) {
$(this).prepend(' ' + (i+1) + ' ');
});
});
$("ol").each
(
function ()
{
$("li", this).each
(
function (i)
{
$(this).prepend("<span>" + (i+1) + "</span>" );
}
);
}
);
精彩评论