2013-02-20 70 views
4

我做了一個每個函數來計算div中的圖像,我試圖設置div內的圖像數作爲div的數據屬性,但它不工作。將數據添加到每個函數中的元素

我是否因爲它似乎不工作而走錯了方向?

這裏是網站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; 

     }     

    }); 
+0

你的意思是不工作?僅供參考,通過jQuery在元素上設置'.data()'_will not_不會顯示爲源中的'data-'屬性。 – jmoerdyk 2013-02-20 23:00:52

回答

14

該數據集以jQuery的專有數據緩存:

$this.data('count', numImages); 

它不設置爲元素的data-屬性。通常不需要在客戶端上設置data-屬性,因爲其目的是將數據從服務器傳輸到客戶端。

不過,如果你想設置它,使用

$this.attr('data-count', numImages) 

this.setAttribute('data-count', numImages) 

個人而言,如果我想要一個小的數據量與元素相關聯,我d直接將它作爲一個屬性存儲在元素本身上。

this.count = numImages; 

對於原始數據,它是無害的。對於較大的對象或其他DOM元素,我會更猶豫。

相關問題