Just started a formal career, the last few days in the company to do a unified head JS, think of a script custom properties to pass configuration parameters method.
Sometimes we write a JS plug-in, to use the plug-in need to first introduce the plug-in JS in HTML, and then add a script tag, called inside. such as a picture switch plugin. The code is roughly as follows:
$.fn.picswitch = function (option) {
//Here is the picture Toggle code
}
After you introduce the plugin, you need to add the calling code to another script tag.
$ (' #pic '). Picswitch ({
' speed ': '), '
derection ': ' Left '
//... Here is the configuration
})
This is certainly not a problem, but sometimes we do not want to add more script tags, if only the script tag, how do we pass the configuration parameters?
At this point we can use custom properties on the script to pass configuration parameters. Before you do this, you have to process the picture switch plug-in. The modified code is as follows:
$.fn.picswitch = function () {
//Here is the picture switch code
};
When you write the plugin, you call it directly.
$ (' This is the selector, which needs to be fetched on the Script tab '). Picswitch (' Here is the configuration parameter that needs to be fetched on the Script tab ');
The next step is to pass the parameters on the script, on the HTML page, the following reference to the JS plug-in.
Finally, modify the plugin to:
$.fn.picswitch = function () {
//Here is the picture switch code
};
Write the plug-in directly after the call to the
var script = $ (' #picSwitch '),//tag id
selector = script.attr (' selector '),
option = Json.parse (script.attr (' option '));/The string on the label needs to be converted to JSON object
$ (selector). Picswitch (option);
This makes it possible to use only one tag, and the configuration changes only need to change the script custom attribute.