I have just started my official career and have been doing unified headline JS for the company in recent days. I have come up with a method to pass configuration parameters through custom attributes of script.
Sometimes we write a js plugin. To use this plugin, we need to first introduce the plugin Js in the html, and then add a script tag and call it in it. Such as a picture switch plugin. The code is roughly as follows:
$.fn.picSwitch = function(option){//Here is the code for image switching}After introducing this plug-in, you need to add the call code to another script tag.
$('#pic').picSwitch({'speed' : '400','derection' : 'left'//... Here is the configuration})Of course there is no problem with this, but sometimes we don’t want to add more script tags. If we only introduce script tags, how to pass configuration parameters?
At this time, we can use the custom properties on script to pass configuration parameters. Before this, you must first process the image switching plug-in. The modified code is as follows:
$.fn.picSwitch = function(){//Here is the code for image switching};//Call the plugin after writing it and call it directly
$('Here is the selector, you need to get it on the script tag').picSwitch('Here is the configuration parameter, you need to get it on the script tag');
Next, pass the parameters on script, and reference the js plugin as follows on the html page.
<head><script src='/script/picSwitch.js' id='picSwitch' obj='#pic' option='{"speed":"400","derection":"left"}'></script></head><body><div id="pic">//This is the specific structure</div></body>Finally, modify the plugin to:
$.fn.picSwitch = function(){//This is the code for image switching};//After writing the plug-in, call var script = $('#picSwitch'), //idselector on the tag = script.attr('selector'), option = JSON.parse(script.attr('option'));//The string on the tag needs to be converted into a json object $(selector).picSwitch(option);This way, the function is realized with only one tag, and the configuration changes only require changing the script custom properties.