[英]Get index of element in array jQuery
I has an array of objects $('selector')
, I want to get index()
of each element and append it to the html of each elemt. 我有一个对象数组
$('selector')
,我想获取每个元素的index()
并将其附加到每个元素的html上。 I can get index of first element just write $('selector').index()
, but how I can get other, and append them to they DOM-objects. 我只要写
$('selector').index()
就可以得到第一个元素的$('selector').index()
,但是我可以得到其他元素,并将它们附加到它们的DOM对象中。 Help, I am new in Javascript and jQuery. 帮助,我是Java和jQuery的新手。
Try this... 尝试这个...
$("selector").each(function(i) {
$(this).html($(this).html() + " " + i);
});
i
will be the index of each selected element and will be appended to the html. i
将是每个选定元素的索引,并将被附加到html。
Here's a jsfiddle example... 这是一个jsfiddle示例...
You can pass a function to the .html()
jQuery method. 您可以将函数传递给
.html()
jQuery方法。 This function will conveniently be called with two parameters, the element index and the current HTML, so what you want is easy: 可以使用两个参数(元素索引和当前HTML)方便地调用此函数,因此您想要的很容易:
$elements.html(function(i, v){
return v + i;
});
Which will give you the index
relative to the selection made. 这将为您提供相对于所选内容的
index
。 If you wanted the index relative to each elements siblings, you would need .index()
: 如果您想要相对于每个元素同级的索引,则需要
.index()
:
$('ul li').html(function(_, v){
return v + $(this).index();
});
Use JQuery.each
: 使用
JQuery.each
:
$('selector').each(function(index) {
console.log(index);
});
Example:
例:
Html: HTML:
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
<div>My Div</div>
JS: JS:
$('div').each(function(index){
var newHtml = $(this).html() + " - Index:" + index;
$(this).html(newHtml);
});
Output: 输出:
My Div - Index:0
My Div - Index:1
My Div - Index:2
My Div - Index:3
My Div - Index:4
My Div - Index:5
My Div - Index:6
My Div - Index:7
My Div - Index:8
Use .each() to select each element, get each index and append each index to all elements matching the selector. 使用.each()选择每个元素,获取每个索引,并将每个索引附加到与选择器匹配的所有元素上。
$("selector").each(function(index) {
var eachIndex = $(this).index();
$(this).append(eachIndex);
});
Try: 尝试:
$.each($('selector'), function() {
$(this)append($(this).index());
});
You can also use eq: 您也可以使用eq:
$('selector').each(function(){
$(this).html('index for this html is ' + $(this).eq());
});
You should iterate using .each
您应该使用
.each
进行迭代
Sample Code: 样例代码:
$("selector").each(function(i, v) {
$(this).append(i);
});
Just cycle through them and the iterator will tell you it's index. 只要循环遍历它们,迭代器就会告诉您它的索引。
var array = $('.someClass');
for(var i=0; i<array.length; i++){
console.log('Element #' + i + ': ' + $(array[i]).text());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.