Use jQuery to get the custom properties for data
- 2020-10-23 20:01:21
- OfStack
Cut the crap and code first
jQuery.fn.dataset = function(attr, val) {
// Get data set
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;
}
// Returns specified data
if (arguments.length == 1 && typeof attr != 'object') {
if(encode(attr) == "data-path"){
return this.attr(encode(attr));
}
return autobox(this.attr(encode(attr)));
}
// Set data set
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);
};
Using jQuery to make components, we can easily get custom properties of data- and assign values to data- properties.
Access to:
$("div").dataset("name") // To obtain data-name The value of the
Assignment:
$("div").dataset("name","Tezml") // to data-name This property is assigned a value of Tezml