Solo  当前访客:0 开始使用

knockout框架学习(一)--virtualElement.js(1)


1、virtualElement.js

利用注释 构建虚拟元素

》IE9无法读取nodeValue属性,但是可使用text属性读取节点内容

 

2、判断使用哪种属性读取 注释节点的内容

var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";

3、判断 起始和关闭标签

var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
    var endCommentRegex =   commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
function isStartComment(node) {
    return (node.nodeType == 8) &amp;&amp; startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}

function isEndComment(node) {
    return (node.nodeType == 8) &amp;&amp; endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}<br /><br /><br /></pre>

  使用方法 <!-- ko if: test --> xxxxxxxx<!-- /ko -->

4、由开始标签 查找匹配的 关闭标签

1)获取当前子元素

function getVirtualChildren(startComment, allowUnbalanced) {
        var currentNode = startComment;
        var depth = 1;
        var children = [];
        while (currentNode = currentNode.nextSibling) { //依次向下查找同级元素
            if (isEndComment(currentNode)) {
                depth--;
                if (depth === 0)
                    return children;
            }
        children.push(currentNode);

        if (isStartComment(currentNode)) // 如果有 起始标签,则 对应的 depth+1, 即 需要找到depth+1个endComment
            depth++;
    }
    if (!allowUnbalanced)
        throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
    return null;
}</pre>

 

2)获取对应的关闭标签

    function getMatchingEndComment(startComment, allowUnbalanced) {
        var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
        if (allVirtualChildren) {
            if (allVirtualChildren.length > 0)
                return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
            return startComment.nextSibling;
        } else
            return null; // Must have no matching end comment, and allowUnbalanced is true
    }


标题:knockout框架学习(一)--virtualElement.js(1)
作者:hugh0524
地址:https://blog.uproject.cn/articles/2017/07/05/1499266296691.html

, , , , 0 0