Home Web Front-end JS Tutorial js how to write plug-in tutorial sharing

js how to write plug-in tutorial sharing

Mar 02, 2018 pm 01:42 PM
javascript share Tutorial

This article mainly shares with you tutorials on how to write plug-ins in js. I hope it can help you.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style type="text/css">
        #demo-1, #demo-2 {
            width: 200px;
            height: 200px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <h3>点击add可以添加个自input的内容到p里并实现变颜色</h3>
    <!--组件实例1-->
    <p id="demo-1">
        <input type="" name="" id="" value="好的" />
        <button id="add-1">add</button>
    </p>
    <br />    <br />
    <!--组件实例2-->
    <p id="demo-2">
        <input type="" name="" id="" value="11" />
        <button id="add-2">add</button>
    </p>
    <script type="text/javascript">
        //这里是插件的代码;我为了方便都写到一个html中了;请把这个script标签中的内容单独写在一个js文件里
        //整个插件写在一个立即执行函数里;就是function(){}();函数自执行;保证里面的变量不会与外界互相影响
        //头部的win啊,doc啊 $  啊都是底部的window,document,jQuery的映射;方便内部直接调用;
        //当然你不引用jq的话头部的$和底部的jQuery干掉;你若引用了更过的依赖可以依次添加;
        //最后面的undefined可不写;最好写了;保证里面再出现的undefined是未定义的意思;不被其他东西赋值;
        //好了下面是时候展现真正的技术了
        //function前的!号(叹号)或者;(分号)这不是写错了,为了防止那个二货写的js结束没有分号;而可能发生报错
        /*
        ;function(win,doc,$,undefined){
       }(window,document,jQuery)或者写在一个闭包里(function(){          }())
         */
        (function (win, doc, undefined) {
            //我们随便写一个插件吧 比如你要点击按钮  添加input的值到 p里
            var addHtml = function (demo, btn) {//插件名,调用的时候直接new一下插件名就行了并传参数或者传对象(一般这个函数名手写字母大写比较好,构造函数嘛,其实也是函数)
                //很明显我要传id名;这里传什么都可以的其实;
                this.p = doc.getElementById(demo);//为什么把获取的id传给this.p呢?this的指向为调用的实例;我们此时姑且认为this就指向这个函数;因为这样我们之后再想获取这个p就可以直接用this.p了好吗;而不是在document.getElementById(。。。。)
                this.btn = doc.getElementById(btn);
                this.Input = this.p.getElementsByTagName("input")[0];//既然找到了p我们在找下p下面的input;当然你要不input用获取id的形式传参数我没有意见
                this.num = 0;//你也可以写一些其他的默认的东西;比如默认的变量啦;方便下面调用;这里写了什么都不会报错;只是有用没用的问题这行可以忽略
                this.author = "lianxiaozhuang";
                this.init();//执行下你下面写的函数吧;你想想;如果整个插件没有执行函数;多不好;一堆方法function就不调用;对;这里是调用的时候最开始执行的函数
            }
            //;给构造函数addHtml对象原型里添加属性(方法)
            addHtml.prototype = {//给函数写方法;这里可能不止一个函数;你还记得你在全局里写一个个的function吗;贼乱;
                //找也不好找;把一个个函数都写到对象的属性里;调用函数就直接调用对象的属性;
                constructor: addHtml,//构造器指向构造函数;这行其实不写没啥毛病;不过有时候防止构造器指向Object的情况;你还是装逼写上吧;
                init: function () {//这里的init;你也可以写成  nimade:function(){ }都没有问题;就是在addHtml函数里this.init();执行下;你明白了这里的this了吧;整个插件里this都是只得这个函数(实例);除非你又引入了其他的函数里的(其他函数里的可能指向就是window了)
                    var _self = this;////把this保存下来防止在局部函数内部取不到(局部函数内部取得this可能是别的)
                    this.btn.onclick = function () {
                        var _val = _self.Input.value;
                        var tempp = doc.createElement("p");//创建临时p存放获取input的值
                        tempp.innerHTML = _val;
                        //console.log(tempp);
                        _self.p.appendChild(tempp);
                        _self.setColor();//你把所有方法都写在init里绝对没问题;还是那句话;说好的松耦合呢;说好的不写一堆堆的function一层层乱套呢
                    };
                },
                setColor: function () {
                    //console.log(this.p)
                    this.p.style.color = "red"
                }/*,
        otherFun(){
            //当然你还可以扩展其他方法;这些方法之间都可以互相调用;
            只要用this.方法名       就行了;如果在取不到this比如上面的click函数中的this指向点击的button;只要在写var _self = this;就可以用_self  代替this(函数实例)了;当然_self  也可以写成别的 比如$this等自定义的
        }*/
            }
            win.addHtml = addHtml;//把这个对象附给window底下的 名字叫addHtml的对象;要不你调用的时候  new addHtml() 怕在window的环境下找不到;
        }(window, document))
    </script>
    <script type="text/javascript">
        new addHtml("demo-1", "add-1");//这里是实例1调用插件的代码
        new addHtml("demo-2", "add-2");    //这里是实例2调用插件的代码
        //是不是明白为什么要写插件了;要封装;两个相同组件即使有相同的class名在dom操作的时候也不会相互冲突;因为他们都new出来了个自的实例;有自己的this;有自己的一套方法了(其实方法都在原型里是公用的;操作各自的dom)
    </script>
    <!--这里是最简单的插件写法;当然还有传对象参数的插件等等。。。。-->
</body>
</html>
Copy after login

Related recommendations:

Jquery operation Select is simple and convenient with a js plug-in_jquery

js implementation of md5 encryption plug-in code sharing

JS code to implement waterfall flow plug-in

The above is the detailed content of js how to write plug-in tutorial sharing. For more information, please follow other related articles on the PHP Chinese website!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

See all articles