At the beginning of my formal career, I have been working on a unified header Js for my company in the last few days. I thought of a method for passing configuration parameters through script custom attributes.
Sometimes we have compiled a JS plug-in. To use this plug-in, we need to first introduce the plug-in JS in HTML, then add a script tag, and call it in it. Such as an image switching plug-in. The code is roughly as follows:
$. FN. picswitch = function (option) {// here is the picture switching code}
After the plug-in is introduced, you need to add the call code in another script tag.
$ ('# PIC'). picswitch ({'speed': '000000', 'derection ': 'left' //... here is the configuration })
Of course, there is no problem, but sometimes we don't want to add more SCRIPT tags. If we only introduce SCRIPT tags, how can we pass the configuration parameters?
At this time, we can use the Custom Attributes on the script to pass the configuration parameters. Before that, you must process the image switching plug-in. The modified code is as follows:
$. FN. picswitch = function () {// here is the code for image switching}; // After writing the plug-in, call $ 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 the script to pass the parameter. The JS plug-in is referenced below on the HTML page.
<Head> <SCRIPT src = '/script/picswitch. JS 'id = 'picswitch' OBJ = '# PIC 'option =' {"Speed": "400", "Derection ": "Left"} '> </SCRIPT>
Finally, modify the plug-in:
$. FN. picswitch = function () {// here is the code for switching images}; // After writing the plug-in, you can directly call var script = $ ('# picswitch '), // ID selector = script on the tag. ATTR ('selector '), option = JSON. parse (script. ATTR ('option'); // the string on the tag needs to be converted into a JSON object $ (selector ). picswitch (option );
In this way, only one tag is used to implement the function. You only need to change the script custom attribute for configuration changes.
Script custom property transfer configuration parameters