对类选择的元素数组使用FOR循环,并对每个元素调用函数

Using a FOR loop for an array of elements selected by class, and calling functions on each

本文关键字:元素 函数 循环 调用 选择 数组 FOR      更新时间:2023-09-26

我正试图在whateverDiv上循环并找到每个元素的偏移量。我收到错误消息Uncaught TypeError: undefined is not a function,我怀疑是因为无法在元素上调用.offset()。这就引出了一个问题,即如何在这样的数组中的元素上调用函数,如.offset().is(":hover")

whateverDiv  = document.getElementsByClassName('whatever')
//RETURNS SOMETHING LIKE [<img src=​"http:​/​/​www.whateversource.jpg">​,<img src=​"http:​/​/​www.whateversource2.jpg">​]
for (i in whateverDiv){
    console.log(whateverDiv[i].offset())
}

假设jquery包含

whateverDiv  = document.getElementsByClassName('whatever')
//RETURNS SOMETHING LIKE [<img src=​"http:​/​/​www.whateversource.jpg">​,<img src=​"http:​/​/​www.whateversource2.jpg">​]
for (i in whateverDiv){
    var $div = $(whateverDiv[i])
    console.log($div.offset())
}

正如其他人提到的,您不应该使用for in,而应该使用标准的for构造。然而,如果你已经在使用jQuery了,你还可以喝koolaide并使用他们的.每个

http://api.jquery.com/each/

$(".whatever").each(function() {
  console.log( $(this).offset() );
});

您已经使用两种类型的for循环的组合对循环进行了编码。

for (i in whateverDiv) {
    // 'i' is each element
}

与。

for (var i = 0; i < whateverDiv.length; i++) {
    // 'i' can be used as an index of the 'whateverDiv' collection
}

然而,正如在评论中所述,最好使用所有jQuery,因为循环中的对象仍需要转换为jQuery对象才能使用这些函数。

$('.whateverDiv').each(function () {
    console.log($(this).offset());
});

您可以使用jQuery循环:

 $('.whatever').each(function(index, value) {
    console.log('Item: ' + index + ' - element: ' + $(value).text());
   // you could call a function like this on each element:
   // yourFunction($(value));
   // or a function of the jQuery element -> $(value).offset();    
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="whatever">
  item one
</div>
<div class="whatever">
  item two
</div>
<div class="whatever">
  item three
</div>
<div class="whatever">
  item four
</div>
<div class="whatever">
  item five
</div>