封装一个可以获取元素文本内容的函数

php中世界最好的语言
php中世界最好的语言 原创
2018-05-24 15:19:37 1434浏览

这次给大家带来封装一个可以获取元素文本内容的函数,封装一个可以获取元素文本内容函数的注意事项有哪些,下面就是实战案例,一起来看一下。

A.1 逻辑步骤

目标: 获取某元素的 所有同级+元素节点

S1 获取某的父元素节点 + 其所有子节点
S2 声明将要返回的伪数组对象
S3 去除本身传入的元素节点
S4 利用 array.length按下标传入数组内容(如果用i,i是有可能跳过的,就不是按序了)
S5 返回这个伪数组

A.1 具体代码

<body>
    <ul>
        <li id="item1">选项1</li>
        <li id="item2">选项2</li>
        <li id="item3">选项3</li>
        <li id="item4">选项4</li>
        <li id="item5">选项5</li>
    </ul>
</body>
//S5 封装为函数(API)
function getSiblings(node){
    var allChildren = node.parentNode.children;     //S1 获取li的父元素节点 + 其所有子节点
    var array = {length:0};                         //S2 声明将要返回的伪数组对象
    for (let i = 0; i < allChildren.length; i++){
        if (allChildren[i] !== node){              // S3 去除本身传入的元素节点
            array[array.length] = allChildren[i];   // S4 利用 array.length按下标传入数组内容(如果用i,i是有可能跳过的,就不是按序了)
            array.length += 1;
            }
        }
        // console.log(array);       // {0:li#item1, 1:li#item2......}
        return array;                // S6 返回这个伪数组
    }

A.2 逻辑步骤

目标: 批量给元素添加/移除类名

S1 遍历对象的key值
S2 当类名的值为ture时,添加类名; 否则则去除

A.2 具体代码

function addClass(node, classes){
    // var classes = {'a':true, 'b':false, 'c':true}   //S1 构造要传入的类名对象
    for (let key in classes){                          //S2 遍历对象的key值
        value = classes[key];
        // if (value){                                    //S3 当类名的值为ture时,添加类名
        //     node.classList.add(key);
        // }else{
        //     node.classList.remove(key);
        // }
        // 以上 if/else可以优化为
        var methodName = value ? 'add':'remove';
        node.classList[methodName](key);
    }
}

B 添加上命名空间,就是

window.mydom = {};
mydom.getSiblings = function getSiblings(node){
    var allChildren = node.parentNode.children;
    var array = {length:0};
    for (let i = 0; i < allChildren.length; i++){
        if (allChildren[i] !== node){              // 去除本身传入的元素节点
            array[array.length] = allChildren[i];
            array.length += 1;
        }
    }
    return array;
}
mydom.addClass = function addClass(node, classes){
    classes.forEach( (value)=> node.classList.add(value) );
}

`
调用方法就是 mydom.getSiblings(item3); mydom.addClass(item3, ['a','b'])
而希望的调用方法是item3.getSibling() / item3.addClass('['a', 'b'])

C.1 this+原型链

Node.prototype.getSiblings = function getSiblings(){
    var allChildren = this.parentNode.children;
    var array = {length:0};
    for (let i = 0; i < allChildren.length; i++){
        if (allChildren[i] !== this){              // 去除本身传入的元素节点
            array[array.length] = allChildren[i];
            array.length += 1;
        }
    }
    return array;
}
Node.prototype.addClass = function addClass(classes){
    classes.forEach( (value)=> this.classList.add(value) );
}
// 参考效果
console.log( item3.getSiblings() )

C.2 node2函数_对象模式

window.Node2 = function(node){         //要挂载到全局window上,才能直接访问
    return {
        getSiblings: function(){
            var allChildren = node.parentNode.children;
            var array = {length:0};
            for (let i = 0 ; i < allChildren.length; i++){
                if (allChildren[i] !== node){
                    array[array.length] = allChildren[i];
                    arrat.length += 1;
                }
            }
            return array;
        },
        addClass: function(classes){
            classes.forEach( (value) => node.classList.add(value) )
        }
    }
}
//参考效果
node2 = Node2(item3);
console.log( node2.getSibling() );
node2.addClass( ['a', 'b', 'c'] )

C.3 模拟一个简化的jQuery

window.jQuery = function(nodeOrSelector){
    let node;
    if (typeof nodeOrSelector === 'string'){        //类型检测
        node = document.querySelector(nodeOrSelector);  //只支持返回一个节点
    } else {
        node = nodeOrSelector;
    }
    return{
        getSibligs: function(){
           var allChildren = node.parentNode.children;
            var array = {length:0};
            for (let i = 0 ; i < allChildren.length; i++){
                if (allChildren[i] !== node){
                    array[array.length] = allChildren[i];
                    arrat.length += 1;
                }
            }
            return array;
        },
        addClass: function(classes){
             classes.forEach( (value) => node.classList.add(value) )
        }
    }
}
//调用效果
var node2 = jQuery('#item3');
node2.getSibling();
node2.addClass(['red', 'c'])

C.4 支持传入 一个/多个节点

window.jQuery = function(nodeOrSelector){
    let nodes = {};  //S1 以后要用到的元素节点伪数组,空对象
    if (typeof nodeOrSelector === 'string'){
        let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组
        for (let i = 0 ; i < temp.length; i++){
            nodes[i]= temp[i];                     //S3 去除多余原型链部分
        }
        nodes.length = temp.length;
    } else if (nodeOrSelector instanceof Node){
        nodes ={ 0: nodeOrSelector , length:1};    //S4 单个元素也要返回伪数组
    }
    nodes.addClass = function(classes){
        // for (let i = 0; i < nodes.length; i++){
        //     classes.forEach( (value) => nodes[i].classList.add(value) );
        // }
        // 更好的写法是
        classes.forEach( (value) => {
            for (let i=0; i<nodes.length; i++){
                nodes[i].classList.add(value);
            }
        })
    }
    return nodes
}
//调用效果
var node2 = jQuery('ul>li');
node2.addClass( ['blue'] );

D 添加其他功能

window.jQuery = function(nodeOrSelector){
    let nodes = {};  //S1 以后要用到的元素节点伪数组,空对象
    if (typeof nodeOrSelector === 'string'){
        let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组
        for (let i = 0 ; i < temp.length; i++){
            nodes[i]= temp[i];                     //S3 去除多余原型链部分
        }
        nodes.length = temp.length;
    } else if (nodeOrSelector instanceof Node){
        nodes ={ 0: nodeOrSelector , length:1};    //S4 单个元素也要返回伪数组
    }
    nodes.addClass = function(classes){
        // 更好的写法是
        classes.forEach( (value) => {
            for (let i=0; i<nodes.length; i++){
                nodes[i].classList.add(value);
            }
        })
    }
    // 获取元素节点文本内容
        // S1 遍历元素节点的伪数组;
        // S2 获取其文本内容,并推送到存储的 数组;
        // S3 返回数组
    nodes.getText = function(){
        var texts = [];
        for (i = 0; i < nodes.length; i++){
            texts.push(nodes[i].textContent);    //获取元素节点内容并推入到数组
        }
        return texts
    }
    // 设置元素节点文本内容
        // S1 遍历元素节点的伪数组;
        // S2 设置其文本内容为传入的参数内容
    nodes.setText = function(text){
        for (i = 0 ; i < nodes.length; i++){
            nodes[i].textContent = text;
        }
    }
    // 合并为一个接口
        //  S1 判断是否传入了参数, 传入了就是设置,没传入就是读取
    nodes.text = function(text){
        if (text === undefined){
            var texts = [];
            for (i = 0; i < nodes.length; i++){
                texts.push(nodes[i].textContent);
            }
            return texts
        } else {
            for (i = 0 ; i < nodes.length; i++){
            nodes[i].textContent = text;
            }
        }
    }
    return nodes
}
// 调用结果
var node2 = jQuery('ul>li');
node2.addClass( ['blue'] );
// 获取文本内容
    // var text = node2.text();
    // console.log(text);
// 设置文本内容
node2.text('hi');

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

js的数组原型方法使用详解

EasyCanvas绘图库在Pixeler项目开发中使用实战总结

以上就是封装一个可以获取元素文本内容的函数的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。