2015-03-30 29 views
0

到的.class元素我試圖數據屬性添加到使用此代碼類元素(的.class):如何添加DATA-(東西)屬性與jQuery

$(".class").data("attribute") === "" ; 

後來與此

$(".class").attr('data-sr',''); 

但是,根本不工作。 Option1根本不工作,而option2只適用於我的情況下的標籤名稱。 有東西被竊聽或我沒有使用好的東西?

回答

0

這是你如何正確地分配和讀取數據使用jQuery的。數據()屬性如下:

// Assign a data attribute 
$(selector).data('my-attr', 'test value'); 

// Read a data attribute 
var value = $(selector).data('my-attr'); 

如果你想添加到DOM本身的數據屬性,你可以使用jQuery的ATTR()作爲如下:

// Assign a data attribute - note the need to prefix it with "data-" 
$(selector).attr('data-my-attr', 'test value'); 

// Read a data attribute - note the need to prefix it with "data-" 
var value = $(selector).attr('data-my-attr'); 

實施例:

$(function() { 
    $(".testclass").data('val', 'something1'); 
    alert($(".testclass").data('val')); 


}); 

小提琴:http://jsfiddle.net/BenjaminRay/hau9gac9/

0

就像.attr(),你給兩個參數來改變數據:

$(".class").data("attribute", "value"); 

請注意,如果您有.data而非.attr添加數據,它存儲在內部內的jQuery,你不會看到它作爲DOM中的data-attribute屬性。 jQuery僅在第一次閱讀時才使用data-attribute屬性作爲值的初始來源。