jquery - Get the occurrence of an element
I have a d开发者_Python百科iv 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
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 outcome 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.
精彩评论