I have just started my official career. In the past few days, I have been working on a unified header js for the company, and I came up with a method of passing configuration parameters through script custom attributes.
Sometimes we write a js plug-in. To use the plug-in, we need to first introduce the plug-in JS in html, and then add a script tag and call it inside. Such as a picture switching plug-in. The code is roughly as follows:
$.fn.picSwitch = function(option){ //这里是图片切换的代码 }
After introducing the plug-in, you need to add the calling code in another script tag
$('#pic').picSwitch({ 'speed' : '400', 'derection' : 'left' //... 这里是配置 })
Of course there is no problem with this, but sometimes we don’t want to add another script tag. If we only introduce the script tag, what should we do and how to pass the configuration parameters?
At this time we can use the custom attributes on the script to pass configuration parameters. Before doing this, the image switching plug-in must be processed first. The modified code is as follows:
$.fn.picSwitch = function(){ //这里是图片切换的代码 };
//After writing the plug-in, call it directly
$('Here is the selector, which needs to be obtained on the script tag').picSwitch('Here is the configuration parameter, which needs to be obtained on the script tag');
The next step is to use script to pass parameters, and reference the js plug-in on the html page as follows.
<head> <script src='/script/picSwitch.js' id='picSwitch' obj='#pic' option='{"speed":"400","derection":"left"}'></script> </head> <body> <div id="pic"> //这里是具体结构 </div> </body>
Finally modify the plug-in to:
$.fn.picSwitch = function(){ //这里是图片切换的代码 }; //写好插件后就直接调用 var script = $('#picSwitch'),//标签上的id selector = script.attr('selector'), option = JSON.parse(script.attr('option'));//标签上的是字符串需要转为json对象 $(selector).picSwitch(option);
In this way, only one tag is used to implement the function. Configuration changes only require changing the script custom attribute.