1

Let's look at the following code:

<ul>
  <li>What is jQuery?</li>
  <li>What is HTML?</li>
  <li>What is CSS</li>
</ul>

What I want to be able to do is to append after each question (into another div) this kind of text: question 1/3, question 2/3 and question 3/3...

I know length() calculates the total number of matched elements so that would give me the number "3" that goes after the "/" but how do I display the current question's number? I know it's something related to index() but I am not sure on how to do this.

Thank you!

4

3 回答 3

1

I'd suggest:

var size = $('li').length;
$('li').each(function(i){
    $('<div />', {'text' : 'Question ' + (i+1) + '/' + size}).appendTo(this);
});

JS Fiddle demo.

于 2013-03-09T01:16:44.233 回答
0

demo: http://jsfiddle.net/tGLQk/1

use each

html

<ul>
  <li>What is jQuery?</li>
  <li>What is HTML?</li>
  <li>What is CSS</li>
</ul>

js

var count = $("ul li").length;
$("ul li").each(function(key,val){
 this.innerHTML += " " + (key+1) + "/"+count;
});
于 2013-03-09T01:17:49.257 回答
-1

无法保证.each顺序正确,但您可以使用 CSS 来做到这一点。参见这个小提琴的例子:http: //jsfiddle.net/NCzsG/

(请注意,如果您有多个列表,则需要在每个列表的s上.each遍历每个ul运行 this 的列表)li

于 2013-03-09T01:26:43.727 回答