You may often see some HTML with data attributes. These are HTML5 Custom Attributes. The following describes how to use them, I hope it will help you. You may often see some HTML with data attributes. These are HTML5 Custom Attributes. You can do a lot of things and it is very convenient to directly call JS, although it is an HTML5 attribute, it is good to use jQuery, so it can be used normally in almost all browsers, including earlier IE versions. The following is a brief introduction to the usage:
1. Easy to use
The Code is as follows:
The Code is as follows:
$ (Function (){
Var _ widget = $ ("# widget "). attr ("data-text"); alert (_ widget); // print 123456 because data-text = "123456"
})
2. Use with $. fn. extend to compile the plug-in
The Code is as follows:
Here is the test area
The Code is as follows:
// Extensions
; (Function ($ ){
$. Fn. extend ({
Test: function (config ){
/**
* @ Param effect
* Config | {} when custom attributes are imported, the default value is not executed.
*/
// Set the 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 Code is as follows:
// Call part. The data attribute in HTML depends on this
$ (Function (){
Var _ widget = $ ("# widget"). attr ("data-widget-config ");
// You can convert a string to a json object using either of the following methods:
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 is called here,
If it is data-widget-config = "{effect: 'mouseover'}", call the move event })