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
6 Answers
Reset to default 8As 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
版权声明:本文标题:javascript - jquery - Get the occurrence of an element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744272951a2598273.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论