1

我正在尝试{{Placeholder}}在文档中查找占位符文本(占位符如下所示:),然后获取它所在的节点,然后向节点添加一个属性。到目前为止,我能够找到占位符,但我不知道它属于哪个元素。当前代码将I am here写入控制台 3 次,因为它位于 3 个节点中htmlbodyh1. 它如何获得项目的实际父节点?

JavaScript:

function getPlaceholders(){
    var elements = document.getElementsByTagName("*");
    for(var e in elements){
        var element = elements[e];
        var html = element.innerHTML;
        if(html && (matches = html.match(/{{(.+)}}/g))){
            console.log("I am here");
        }
    }
}

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <h1>Hello {{name}}!</h1>
    </body>
</html>
4

2 回答 2

3

这有效:(来自这里的代码)

function getPlaceholders(){
    var elements = document.getElementsByTagName("*");
    for(var e in elements){
        var element = elements[e];
        child = element.firstChild,
        texts = [];

        while (child) {
            if (child.nodeType == 3) {
                texts.push(child.data);
            }
            child = child.nextSibling;
        }

        var html = texts.join("");
        if(html && (matches = html.match(/{{(.+)}}/g))){
            console.log(html);
        }
    }
}

http://jsfiddle.net/wumm/2VjVa/(忽略第一个日志,这只是 jsfiddle 的构建方式)

于 2013-11-08T16:24:07.980 回答
0

我相信这只能通过递归来实现

function getPlaceholders(elem) {
    // we search for the {{...}} pattern ONLY for this element
    var html = elem.firstChild.data;
    if(html && (matches = html.match(/{{(.+)}}/g))){
        console.log(elem, "I am here");
    }

    // if there are any descendants of this elem, we also call the getPlaceholders function for them
    var elements = elem.children;
    if (elements.length) {
        for(var i = 0; i < elements.length; i++) {
            getPlaceholders(elements[i]);
        }
    }
}

//starting at the body
getPlaceholders(document.body);

这是一个例子:http: //jsfiddle.net/Ng7j8/

于 2013-11-08T16:42:31.827 回答