美文网首页
自制jQuery函数实现修改元素样式及文本内容

自制jQuery函数实现修改元素样式及文本内容

作者: Mr_LvHeng | 来源:发表于2019-05-29 17:53 被阅读0次

    源代码

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            .red {
                color: red;
            }
        </style>
    </head>
    
    <body>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <script>
            window.jQuery = function (nodeOrSelector) {
                let nodes = {}
                if (typeof nodeOrSelector === 'string') {
                    let temp = document.querySelectorAll(nodeOrSelector)
                    for (let i = 0; i < temp.length; i++) {
                        nodes[i] = temp[i]
                    }
                    nodes.length = temp.length
                } else if (nodeOrSelector instanceof Node) {
                    nodes = {
                        0: nodeOrSelector,
                        length: 1
                    }
                }
                nodes.addClass = function (classes) {
                    for (let i = 0; i < nodes.length; i++) {
                        nodes[i].classList.add(classes)
                    }
                }
                nodes.setText = function (text) {
                    for (let i = 0; i < nodes.length; i++) {
                        nodes[i].textContent = text
                    }
                }
                return nodes
            }
    
            window.$ = jQuery
            var $div = $('div')
            $div.addClass('red') // 可将所有 div 的 class 添加一个 red
            $div.setText('hi') // 可将所有 div 的 textContent 变为 hi
        </script>
    </body>
    </html>
    

    代码实现过程

    1. 首先window.jQuery创造全局的构造函数
    2. 先判断传入的参数是单个选择器还是多个选择器,如果是多个选择器则遍历它们放到新的伪数组中,如果是单个选择器,则直接将它放到伪数组中第 0 个的位置,并赋值 length 为 1
    3. 给元素追加样式:通过for循环遍历伪数组中的每一个元素,并给它们添加相应的样式,来给每一个元素追加样式
    4. 修改元素文本内容:同样用for循环遍历的方法遍历每个元素,并修改它们的文本内容

    相关文章

      网友评论

          本文标题:自制jQuery函数实现修改元素样式及文本内容

          本文链接:https://www.haomeiwen.com/subject/tgqutctx.html