admin管理员组

文章数量:1401291

I have a div which contains 5 images.

I want to write to a p tag every occurrence of the img

$("#myDiv img").each( function() {
    $("p").append($(this).length);
});

The above returns:

11111

What I want to return is:

12345

I have a div which contains 5 images.

I want to write to a p tag every occurrence of the img

$("#myDiv img").each( function() {
    $("p").append($(this).length);
});

The above returns:

11111

What I want to return is:

12345

Share Improve this question asked Mar 9, 2011 at 13:48 TomTom 13k50 gold badges153 silver badges247 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 8

As per jQuery API documentation, you can pass the index as the first argument to the function. Thus:

$("#myDiv img").each( function(i) {
  $("p").append(i+1);
});

I'm not really sure If if I get you right, but the desired oute should be when invoking .index() to get the index within the siblings:

$("#myDiv img").each( function() {
    $("p").append($(this).index()+1);
});

Since the index is zero-based, I increment those values by one here.

Probably a bette way is to just use the index which gets passed into the callback method of .each().

$("#myDiv img").each(function(index) {
    $("p").append(index + 1);
});

You're looping trough each image found in your #myDiv element and then you echo the length of the current element - which will always be 1.

var i = 1;

$("#myDiv img").each( function() {
    $("p").append(i);
    i++;
});

Classic example of incrementing a counter variable.

Why not just do it like this?

var no = 1;

$("#myDiv img").each( function() {
    $("p").append(no);
    no++;
});

You'll have to make use of a global variable like so:

var cnt = 0;

$("#myDiv img").each( function() {
    $("p").append(++cnt);
});

This should work.

How about:

var index = 0;
$("#myDiv img").each( function() {
    $("p").append(++index);
});

You are always accessing ONE element out of 5 when each() is called, so you always get length 1.

本文标签: javascriptjqueryGet the occurrence of an elementStack Overflow