• 技术文章 >web前端 >js教程

    jQuery的用法介绍(代码)

    不言不言2019-03-23 15:54:01转载820

    本篇文章给大家带来的内容是关于jQuery的用法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

    代码部分

    <script>
            window.jQuery=function(nodeOrSelector){
                let nodes={}
                let node1=[]
                if(typeof nodeOrSelector==='string'){
                   let temp=document.querySelectorAll(nodeOrSelector)
                   for(let i=0;i<temp.length;i++){
                       node1[i]=temp[i]
                   }
                
                }else if(nodeOrSelector instanceof Node){
                    node1={
                        0:nodeOrSelector,
                        length:1
                    }
                }
                nodes.addClass=function(classes){
                    classes.forEach(value => {
                        for(let i=0;i<node1.length;i++){
                            node1[i].classList.add(value)
                        }
                    })
                
                }
    
                 nodes.setText=function(text){
                    for(let i=0;i<node1.length;i++){
                        node1[i].textContent=text
                    }
                }
                return nodes   
            }
            window.$=jQuery
            var $p=$('p')
            $p.addClass(['red'])
            $p.setText('hi')
    </script>

    思路

    首先声明函数jQuery()并在函数中声明一个封装了两个函数的对象,以实现给元素加class和添加文本的功能;
    其次在函数中判断所传参数是否为字符串还是节点;
    接着编写addClass与setText方法;
    最后返回对象nodes,可以调用对象中的方法,大功告成。

    本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的jQuery视频教程栏目!

    以上就是jQuery的用法介绍(代码)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除
    专题推荐:javascript
    上一篇:JavaScript实现递归算法的方法介绍 下一篇:promise是什么?怎么用?
    大前端线上培训班

    相关文章推荐

    • jQuery如何删除元素?remove()、detach()和empty()的简单比较• jquery ui的使用教程有哪些?• jQuery unbind方法如何使用• jQuery方法的总结(附示例)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网