简体   繁体   中英

Loop Attribute number increasing the value by 5 each time

I would like to add an attribute to the div below. However I want each value to increase by 5 . For some reason when I try the code below, it repeats the number rather than increasing it by 5 .

<div class="yo">TOOTO</div>
<div class="yo">TOOTO</div>
<div class="yo">TOOTO</div>
<div class="yo">TOOTO</div>
var text = "";
var i = 0.7;
while (i < 80) {
    $('.yo').attr('wow', i)
    i += 5
}
var text = "";
var i = 0.7;
var j = 0;
while (i < 80) {

 $('.yo').eq(j).attr('wow', i)
 j++;
 i+=5
}

Select one element at the time, $('.yo') returns an array.

EDIT

Consider replacing while(i < 80) with while($('.yo).eq(j)) if you want to set attribute in all the elements.

In your code $('.yo').attr('wow', i) will update attribute value of all elements with class yo .

Use attr() method with a callback which iterates over the elements and then generates the attribute value based on the index of the element.

var i = 0.7;

$('.yo').attr('wow', function(i1) {
  return i + i1 * 5;
})

 var i = 0.7; $('.yo').attr('wow', function(i1) { return i + i1 * 5; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="yo"> TOOTO </div> <div class="yo"> TOOTO </div> <div class="yo"> TOOTO </div> <div class="yo"> TOOTO </div> 

let yo = document.getElementsByClassName("yo");
let i = 0.7;
while (i < 80) {
    yo.forEach((v, index) => v.setAttribute('wow', (index + 1) * i));
    i += 5;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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