Reputation: 626
I made an each function that counts the images inside a div and I am trying to set the number of images counted inside the div as a data attribute for the div but it is not working.
Have I gone about this the wrong way because it does not seem to be working?
Here is the site http://www.touchmarketing.co.nz/test/
var mostImages = 0;
numSliders = $wowSlides.length,
lastVindex = numSliders-1;
$wowSlides.each(function(){
var $this = $(this),
$images = $this.find('img'),
numImages = $images.length;
$images.css({width:$slideWidth, 'float':'left', 'position':'relative'}).wrapAll('<div class="slider" />');
$slider = $this.find(".slider");
$slider.width($slideWidth*numImages).css({'float':'left'});
$this.data('count', numImages); // add data-count="insert number here" to this .wowSlides div
console.log(numImages);
if(numImages > mostImages){
mostImages = numImages;
}
});
Upvotes: 5
Views: 11383
Reputation: 9336
This sets data to jQuery's proprietary data cache:
$this.data('count', numImages);
It doesn't set to a data-
attribute of the element. Generally there shouldn't be a need to set a data-
attribute on the client, since its purpose is to transfer data from server to client.
Nevertheless, if you want to set it, use
$this.attr('data-count', numImages)
or
this.setAttribute('data-count', numImages)
Personally, if I wanted to associate a small amount of data with an element, I'd just store it as a property directly on the element itself.
this.count = numImages;
For primitive data, it's harmless. For larger objects or other DOM elements, I'd be more hesitant.
Upvotes: 16