简体   繁体   English

通过循环动态jQuery选择器?

[英]Dynamic jQuery selector through a loop?

How do I loop through a set of numbers to target my elements? 如何遍历一组数字以定位元素? Eg. 例如。

    for ( i = 1; i < 9; i++ ) {
        $( 'myPetal'+i ).myX = 500;
        $( 'myPetal'+i ).myY = 500;
    }

Don't forget in in jQuery you still need selectors: 不要忘记在jQuery中您仍然需要选择器:

For IDs you would do 对于ID,您会这样做

 for ( var i = 1; i < 9; i++ ) {
      $( '#myPetal'+i ).myX = 500;
      $( '#myPetal'+i ).myY = 500;
 }

And for classes 和上课

for ( var i = 1; i < 9; i++ ) {
         $( '.myPetal'+i ).myX = 500;
         $( '.myPetal'+i ).myY = 500;
    }

Your code sample would look for <myPetal[i]> in the DOM. 您的代码示例将在DOM中查找<myPetal[i]>

You can avoid the loop and instead use the prefix myPetal in the query to get all elements that has a class that starts with that value: 您可以避免循环,而可以在查询中使用前缀myPetal来获取具有以该值开头的类的所有元素:

$("*[class^='myPetal']").attr('myY', 500);

Same idea could be applied in case of using other attributes 如果使用其他属性,则可以应用相同的想法

 $('.class1').attr('myX', 500); $('.class1').attr('myY', 500); $('.class1').html('myX : '+$('.class1').attr('myX') + ' myY : '+$('.class1').attr('myY')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="class1">class1</div> <div class="class1">class1</div> <div class="class1">class1</div> 

if you have the same class for the elements and the value you want to add is same you can do it this way, or you can loop it using .each() function like this 如果元素具有相同的类,并且要添加的值相同,则可以这样做,也可以使用.each()函数将其循环

$('.class1').each(function(){
   $(this).attr('myX', 500);
   $(this).attr('myY', 500);
})

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

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