search
HomeWeb Front-endJS TutorialJavaScript tab plug-in example code_javascript skills

Today, let’s start with the simplest one, rewriting an existing tab switching function into a javascript plug-in.

How to write native functions

The easiest way to rewrite a javascript method as a js plug-in is to mount this method under the window global object

Let’s first take a look at the most original code written using functions:

tab.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="renderer" content="webkit">
<title>jquery_hjb_tab插件demo</title>
<link rel="stylesheet" href="h.css"/>
</head>
<body>
<div id="tab">
<div class="tabs">
<ul>
<li><a href="#">tab1</a></li>
<li><a href="#">tab2</a></li>
<li><a href="#">tab3</a></li>
<li><a href="#">tab4</a></li>
</ul>
</div>
<div class="tabCons">
<section>内容一</section>
<section>内容二</section>
<section>内容三</section>
<section>内容四</section>
</div>
</div>
<script>
window.onload = h_tab('tab');
function h_tab(tabId){
var oLinks = document.getElementById(tabId).getElementsByTagName("a");
var oCons = document.getElementById(tabId).getElementsByTagName("section");
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}

}
}
</script>

h.css

@charset "utf-8";
/*
//author:hjb2722404
//description:
//date:2016/2/18
*/
.tabs ul { width: 100%; list-style-type: none;}
.tabs ul li { width: 48%; display: inline-block; margin: 0; padding: 0;}
.tabs ul li a {border-bottom: 3px solid #cccccc; width: 100%; height: 100%; display: block; text-align: center; min-height: 40px; line-height: 40px; text-decoration: none; font-family: "微软雅黑"; color: #a94442}
.tabs ul li a.cur { border-bottom: 3px solid #f26123;}
.tabCons section { display: none;}
.tabCons section:nth-child(1) { display: block;}

The above two codes are basic codes, and we will improve them step by step based on this code.

Native plug-in writing method

Okay, now, let’s rewrite this method into a plug-in mounted under the window object:

tab.html

……
// 下面是第一次改动
<script type="text/javascript" src="h_tabs.js"></script>
<script>
H_tab("tab");
</script>
</body>
</html>

h_tabs.js

window.H_tab = function(tabId){
var oLinks = document.getElementById(tabId).getElementsByTagName("a");
var oCons = document.getElementById(tabId).getElementsByTagName("section");
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}
}
};

However, we found that although this way of writing is very simple, it also has problems: window is a global object. If we mount all our methods under it and use it as a plug-in, when there are too many plug-ins, it is easy to create a namespace. Conflict, on the other hand, although using native js can reduce external dependence, the amount of code is still relatively large and the writing method is relatively cumbersome.

jquery writing method

We try to introduce the jquery library and rewrite this plug-in into a jquery plug-in.

The jquery plug-in has three forms: class-level form, object-level form, and jquery UI component form

How to write jquery class-level plug-ins – single method

Let’s first look at the form of class-level plug-ins.

In the form of the first category-level plug-in, this method is directly mounted to the root space of jquery as a tool method:

tab.html

……
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="h_tabs.js"></script>
<script>
$.h_tab('tab');
</script>
</body>
</html>

h_tabs.js

$.h_tab = function(tabId){
var oLinks = document.getElementById(tabId).getElementsByTagName("a");
var oCons = document.getElementById(tabId).getElementsByTagName("section");
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}
}
};

How to write jquery class-level plug-ins - multiple methods

If you want to bind multiple methods to the jquery root space, then write like this:

tab.html

……
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="h_tabs.js"></script>
<script>
$.h_tab('tab');
$.h_hello('hjb');
</script>
</body>
</html>

h_tabs.js

$.extend({
h_tab:function(tabId){
var oLinks = document.getElementById(tabId).getElementsByTagName("a");
var oCons = document.getElementById(tabId).getElementsByTagName("section");
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}
}
},
h_hello :function(name){
console.log("hello,",name);
}
});

Although it is simple and trouble-free to use the $.extend() tool method to mount your own functions directly into the jquery root namespace, unfortunately, this method cannot take advantage of jquery’s powerful sizzle engine, that is, This method cannot be applied to the DOM element you selected.

So we need to use the object-level plug-in development method.

How to write jquery object level plug-in

The object-level plug-in development method is to use the $.fn.extend() method to bind its own method to the jquery prototype, so that all jquery object teams can apply this method to perform corresponding operations

The code is as follows:

tab.html

……
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="h_tabs.js"></script>
<script>
//对象级别的插件引用方法,注意和上面类级别插件的写法上的区分
$('#tab').h_tab('tab');
</script>
</body>
</html>

h_tabs.js

(function($){
$.fn.extend({
h_tab:function(tabId){
var oLinks = document.getElementById(tabId).getElementsByTagName('a');
var oCons = document.getElementById(tabId).getElementsByTagName('section');
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}
}
}
});
})(jQuery);

Here, we use a closure to encapsulate the plug-in to avoid namespace pollution

Here, there are still some problems, that is, our method must pass parameters before it can be run. This causes us to use $('#tab') to select the div with the id of tab when calling, and then in the plug-in we The element is obtained again based on the passed in ID.

Now that we have used jquery’s selector, we can introduce this to solve the redundant problem of repeatedly obtaining elements.

jquery object level plug-in writing method - introduce this

tab.html

……
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="h_tabs.js"></script>
<script>
$('#tab').h_tab();
</script>
</body>
</html>

h_tabs.js

(function($){
$.fn.extend({
h_tab:function(){
//在这里引入this
var oLinks = this.find('a');
var oCons = this.find('section');
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
this.className="cur";
oCons[this.index].style.display ="block";
}
}
}
});
})(jQuery);

What needs to be noted here is that the element object we call the plug-in is ('tab'), so using this.find() directly at this time is equivalent to ('tab').find(), not $ (this).find(), pay attention to using the substitution method to distinguish the difference between the two writing methods.

As a plug-in, it should be controllable by developers, so it should also provide users with some configuration interfaces.

jquery object level plug-in writing method - adding configuration items

tab.html

……
<ul>
<!--对照文章开始的代码, 注意这里的改动 -->
<li><a href="#" class="current">tab1</a></li>
<li><a href="#">tab2</a></li>
……
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="h_tabs.js"></script>
<script>
$('#tab').h_tab({
//使得当前选项卡标签的样式名称可自定义的配置
curName:'current'
});
</script>
</body>
</html>

We changed the initial "current tab label style class name" from "cur" to "current" and passed it into the plug-in as a configuration item

h.css

.tabs ul { width: 100%; list-style-type: none;}
.tabs ul li { width: 48%; display: inline-block; margin: 0; padding: 0;}
.tabs ul li a {border-bottom: 3px solid #cccccc; width: 100%; height: 100%; display: block; text-align: center; min-height: 40px; line-height: 40px; text-decoration: none; font-family: "微软雅黑"; color: #a94442}
/*注意下面一行与之前的样式代码的对比变化之处*/
.tabs ul li a.current { border-bottom: 3px solid #f26123;}
.tabCons section { display: none;}
.tabCons section:nth-child(1) { display: block;}

We have made corresponding changes in the stylesheet.

h_tabs.js

(function($){
$.fn.extend({
//给方法传入一个对象作为参数
h_tab:function(opts){
//定义默认的配置
var defaults ={
curName : 'cur'
};
//将传入的参数覆盖默认参数中的默认项,最终合并到一个新的参数对象上
var Opt = $.extend({},defaults,opts);
var oLinks = this.find('a');
var oCons = this.find('section');
for(var i = 0; i<oLinks.length; i++){
oLinks[i].index = i;
oLinks[i].onclick = function () {
for(var j =0; j<oLinks.length; j++){
oLinks[j].className="";
oCons[j].style.display = "none";
}
//在这里使用配置项的值
this.className = Opt['curName'];
oCons[this.index].style.display ="block";
}
}
}
});
})(jQuery);

Here we use the merge object function of jquery's $.extend() method to overwrite the default configuration items with the configuration items passed in by the user and finally merge them into a new configuration item for use by subsequent programs.

The above is the JavaScript tab plug-in example code introduced by the editor. I hope it will be helpful to everyone!

Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

10 jQuery Syntax Highlighters10 jQuery Syntax HighlightersMar 02, 2025 am 12:32 AM

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

10  JavaScript & jQuery MVC Tutorials10 JavaScript & jQuery MVC TutorialsMar 02, 2025 am 01:16 AM

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool