You may often see some HTML with data attributes. These are custom attributes of HTML5. They can do a lot of things and are very convenient to call JS directly. Although they are attributes of HTML5, fortunately, jQuery is universal, so they can be used normally in basically all browsers, including lower versions of IE. Here is a brief introduction to how to use it: 1. Easy to use Copy code The code is as follows:<div id="widget" data-text="123456"></div> Copy code The code is as follows:$(function(){ var _widget = $("#widget").attr("data-text"); alert(_widget); //Because data-text="123456", it prints out 123456 }) 2. Use with $.fn.extend to write plugins Copy code The code is as follows:<div id="widget" data-widget-config="{effect:'click'}">This is the test area</div> Copy code The code is as follows://Plugin extension part ;(function($){ $.fn.extend({ Test:function(config){ /** * @param effect effect * config||{} When custom properties are passed in, the default value is not executed */ // Set default values 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://Calling part, the data attribute in HTML depends on this $(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 data-widget-config="{effect:'mouseover'}", the event of mouse moving over is called}) |
<<: Detailed explanation of various methods of Vue component communication
>>: CSS3 flip card number sample code
BFC BFC: Block Formatting Context BFC layout rule...
Using UNION Most SQL queries consist of a single ...
When rendering Markdown before, I used the previe...
Table of contents Hidden, descending, and functio...
Preface Since the most important data structure i...
HTML is the abbreviation of Hypertext Markup Langu...
Table of contents 1. setState() Description 1.1 U...
1.MySQL UPDATE JOIN syntax In MySQL, you can use ...
In daily development tasks, we often use MYSQL...
Library Operations Query 1.SHOW DATABASE; ----Que...
Preface Js is the most commonly used code manipul...
HTML meta tag HTML meta tags can be used to provi...
Table of contents 01 Introduction to YAML files Y...
This article uses examples to illustrate the synt...
Table of contents Overview CommonJS Specification...