使用jQuery获取data-的自定义属性
废话少说,先上代码
jQuery.fn.dataset = function(attr, val) { // 获取数据集 if (arguments.length == 0) { var dataset = {}; jQuery(this).eq(0).each(function() { var attrs = this.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attr = attrs[i]; if (/^data-/i.test(attr.name)) { dataset[decode(encode(attr.name.substring(5)))] = autobox(attr.value); if (decode(encode(attr.name.substring(5))) == "path") { dataset[decode(encode(attr.name.substring(5)))] = attr.value != null ? String(attr.value) : null; } if (decode(encode(attr.name.substring(5))) == "name") { dataset[decode(encode(attr.name.substring(5)))] = attr.value != null ? String(attr.value) : null; } } } }); return dataset; } // 返回指定数据 if (arguments.length == 1 && typeof attr != 'object') { if(encode(attr) == "data-path"){ return this.attr(encode(attr)); } return autobox(this.attr(encode(attr))); } // 设置数据集 var dataset = attr; if (typeof attr != 'object') { dataset = {}; dataset[attr] = String(val); } var tmp = {}; jQuery.each(dataset, function(k, v) { tmp[encode(k)] = autobox(v); }); return this.attr(tmp); };
通过jQuery制作组件,可以轻松获取到我们data-的自定义属性,也可以给data-属性来赋值。
获取:
$("div").dataset("name") //获取data-name的值
赋值:
$("div").dataset("name","Tezml") //给data-name这个属性赋值为Tezml
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17