A method of passing configuration parameters through script custom attributes _javascript tips

Source: Internet
Author: User
Tags script tag

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.