Introduction to the use of data custom attribute and plug-in application in HTML

Time:2021-1-22

You may often see that some HTML has data attributes. These are HTML5 custom attributes. You can do a lot of things. It’s very convenient to call JS directly. Although they are HTML5 attributes, the good thing is that jQuery is universal, so they can be used normally in all browsers, including low version ie. Here is a brief introduction to how to use it:
1. Easy to use

Copy code

The code is as follows:

<div data-text=”123456″></div>
Copy code

The code is as follows:

$(function(){
var _ widget= $(“#widget”).attr(“data-text”);   alert(_ Widget); / / 123456 is printed because of data text = “123456”
})

2. Match $ fn.extend Use, write plug-ins

Copy code

The code is as follows:

< div data widget config = {effect: ‘click’} > here is the test area < / div >
Copy code

The code is as follows:

//Plug in extensions
;(function($){
$.fn.extend({
Test:function(config){
/**
*@ param effect
*Config | {} does not execute the default value when a custom attribute is passed in
*/
//Set default
config=$.extend({
effect:’click’,
},config||{});
var effect=config.effect;
var _text=config._text;
if(effect==’click’){
$(this).click(function(){
alert(‘this click’);
})
}else if(effect==’mouseover’){
$(this).mouseover(function(){
alert(“this is mouseover”);
})
}
}
})
})(jQuery)
Copy code

The code is as follows:

//The data property in HTML depends on the call part
$(function(){
var _widget= $(“#widget”).attr(“data-widget-config”);
//There are two ways to convert a string into a JSON object
var widgetConfigJSON=eval(“(“+_widget+”)”);
// var widgetConfigJSON = (new Function(“return ” + _widget))();
$(“#widget”).Test(widgetConfigJSON);
/ / because the data attribute in html is data widget config = {effect: ‘click’} “, the click event will be called here,
If it is data widget config = {effect: ‘mouseover’} “, call the mouse up event})