简体   繁体   English

如何迭代jQuery中的一系列类

[英]How to iterate through a series of Classes in jQuery

I have a series of elements, all of the same class. 我有一系列元素,都属于同一类。

<img class="clicker" src="#"/>
<img class="clicker" src="#"/>
<img class="clicker" src="#"/>

I want to be able to iterate through these classes and alert each of their src attributes to the user using jQuery. 我希望能够遍历这些类,并使用jQuery向用户提醒其每个src属性。

var one = $('.clicker').attr('src');
    alert(one);
    while($('.clicker').next().length){
        ...
        ...
    alert(next src);
    }

I'm not really sure how to write this while loop, or if there is something better to use than while in this instance. 我不太确定如何编写while循环,或者在这种情况下是否比使用while更好。 How should I do this? 我应该怎么做?

You need the following: 您需要以下内容:

$(".clicker").each( function() {
  alert($(this).attr('src'));
});

Use jquery each to loop over 使用jquery each循环

 $('img.clicker').each(function(i, v) { alert($(this).attr('src')) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img class="clicker" src="#" /> <img class="clicker" src="#" /> <img class="clicker" src="#" /> 

Fairly simple as follows 相当简单如下

$(".clicker").each( () =>{
  //Your code
});

Example code in fiddle 小提琴中的示例代码

$('.clicker').each(function(){
    console.log($(this).attr('id')); // used id instead of src as src doesn't have any value other than #
});

Try this 尝试这个

$( ".clicker" ).each(function() {
      console.log( $( this ).attr('src') );
    });

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM