You may often see some HTML with data attributes. These are custom attributes of HTML5 and can do many things. It is very convenient to directly call JS. Although they are attributes of HTML5, fortunately they are common to jQuery, so they are basically It can be used normally in all browsers, including lower versions of IE. Here is a brief introduction to how to use it:
1. Simple use
$(function(){
var _widget= $("#widget").attr("data -text"); alert(_widget);//Because data-text="123456", print out 123456
})
2. Use it with $.fn.extend and write Plug-in
//Plug-in extension part
;(function($){
$.fn.extend({
Test:function(config){
/**
* @param effect effect
* config||{} does not execute the default value when custom attributes are passed in
*/
// Set default value
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)
//The calling part, the data attribute in HTML depends on this
$(function(){
var _widget= $("#widget").attr("data-widget-config");
// There are two ways to convert string into 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'}", then call the event when the mouse moves up})