Implement a compatible version of element.dataset

In order to achieve lazy loading of pages, we often need to implement the use of custom attributes. For details click to open the link

In order to get custom properties, we often need the element.dataset property.

The following code implements a compatible version of the element.dataset property.

Implementation ideas:

1. For compatible element.dataset properties, use this method directly.

2. For those that are not compatible with this method, traverse all attributes of the element and find the attribute.

code show as below:

function dataset(element) {
	var obj={}; //Properties used to store objects
	var key,value,keyname;

	if(element.dataset){
		return element.dataset
	}else{
		var attrs=element.attributes; //Get the attribute object of the element. The return value is an object
		var len=attrs.length;
		for (var i = 0; i <len; i ++) {
			key=attrs[i].name;
			if(key.indexOf("data-")>-1){ //You can use regular /^data-\w+$/g.test(key)
				
				 value=attrs[i].value;
				// var keyname=key.match(/^data-(\w+)$/)[1]; You can use regular to get attribute name
				 keyname=key.slice(5);
				 obj[keyname]=value;
			}
		 }
		return obj;
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325888382&siteId=291194637