Home > Web Front-end > JS Tutorial > body text

Encapsulates a function that can obtain the text content of an element

php中世界最好的语言
Release: 2018-05-24 15:19:37
Original
2070 people have browsed it

This time I will introduce to you the encapsulation of a function that can obtain the text content of an element. What are the precautions for encapsulating a function that can obtain the text content of an element? The following is a practical case, let's take a look. A.1 Logical steps

Goal: Get all sibling element nodes of an element

S1 Get the parent element node of an element and all its child nodes

S2 Statement The pseudo array object to be returned

S3 Remove the element node passed in by itself
S4 Use array.length to pass in the array content by subscript (if i is used, it is possible to skip it, and it is not in order )
S5 Return this pseudo array

A.1 Specific code

<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>
Copy after login
//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 返回这个伪数组
    }
Copy after login

A.2 Logical steps

Goal: Add/remove class names to elements in batches

S1

Traverse the key value of the object

S2 When the value of the class name is true, add the class name; otherwise, remove it
A.2 Specific code

function addClass(node, classes){
    // var classes = {&#39;a&#39;:true, &#39;b&#39;:false, &#39;c&#39;: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 ? &#39;add&#39;:&#39;remove&#39;;
        node.classList[methodName](key);
    }
}
Copy after login

B Add the

namespace

, which is
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) );
}
Copy after login
`The calling method is

mydom.getSiblings(item3); mydom.addClass(item3, [' a','b'])
The desired calling method isitem3.getSibling() / item3.addClass('['a', 'b'])
C.1 this prototype chain

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() )
Copy after login

C.2 node2 function_object mode

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'] )
Copy after login

C.3 Simulate a simplified 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'])
Copy after login

C.4 Support Pass in one/multiple nodes

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(&#39;ul>li');
node2.addClass( ['blue'] );
Copy after login

D Add other functions

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(&#39;ul>li');
node2.addClass( ['blue'] );
// 获取文本内容
    // var text = node2.text();
    // console.log(text);
// 设置文本内容
node2.text('hi');
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the use of array prototype methods in js


Practical use of EasyCanvas drawing library in Pixeler project development Summarize

The above is the detailed content of Encapsulates a function that can obtain the text content of an element. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template