Home > Web Front-end > HTML Tutorial > Introduction to the use of data custom attributes in HTML and plug-in applications_HTML/Xhtml_Web page production

Introduction to the use of data custom attributes in HTML and plug-in applications_HTML/Xhtml_Web page production

WBOY
Release: 2016-05-16 16:40:15
Original
1491 people have browsed it

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

Copy the code
The code is as follows:




Copy code
The code is as follows:

$(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

Copy code
The code is as follows:

This is the test area



Copy the code
The code is as follows:

//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)


Copy code
The code is as follows:

//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})
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template