For this segment of code:
for (var i = 0; i < numbers.length; i++) {
var imageCrystal = $('<img>');
imageCrystal.attr('data-num', numbers[i]);
....
}
is, imageCrystal.attr('data-num', numbers[i]); making a data attribute for the image tag that was just created and giving it a class name called "data-num" and then assigning whatever the value is at number[i]?
Sushanth --
55.8k9 gold badges70 silver badges109 bronze badges
asked Oct 14, 2016 at 22:42
henhen
1571 gold badge1 silver badge12 bronze badges
1 Answer 1
Simply put
imageCrystal.attr('data-num', numbers[i]); is a setter
imageCrystal.attr('data-num'); is a getter
If var numbers = [100, 200, 300] and if the img tags are appended to the DOM, it would look something in these lines.
<img data-num="100" />
<img data-num="200" />
<img data-num="300" />
More info: http://api.jquery.com/attr/
answered Oct 14, 2016 at 22:44
Sushanth --
55.8k9 gold badges70 silver badges109 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
henhen
thank you for the clarification also. I am new to jquery and am still trying to understand the syntax of jquery.
default
data-are an HTML5 thing for storing data in the element. So ifnumbers[i]was 3, this would make animageCrystalelement that looks like<img data-num="3" />. Data attributes can also be accessed using the jQuerydatafunction, soimageCrystal.data("num")should return 3.imageCrystal.data('num', numbers[i]);also if you use thedata()method.