Home > Web Front-end > JS Tutorial > A method to pass configuration parameters through script custom attributes_javascript skills

A method to pass configuration parameters through script custom attributes_javascript skills

WBOY
Release: 2016-05-16 16:36:20
Original
1427 people have browsed it

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){
//这里是图片切换的代码
}
Copy after login

After introducing the plug-in, you need to add the calling code in another script tag

$('#pic').picSwitch({
'speed' : '400',
'derection' : 'left'
//... 这里是配置
})
Copy after login

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(){
//这里是图片切换的代码
};
Copy after login

//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>
Copy after login

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);
Copy after login

In this way, only one tag is used to implement the function. Configuration changes only require changing the script custom attribute.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template