Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add data to element in each function

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;

        }                   

    });
like image 446
Chris G-Jones Avatar asked Feb 20 '13 22:02

Chris G-Jones


1 Answers

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.

like image 132
the system Avatar answered Sep 29 '22 04:09

the system