使用 html <template>:innerHTML.replace

5 html javascript substitution html5-template

最流行的介绍说,我可以很容易克隆的HTML模板我的文档中。

<template id="mytemplate">
  <img src="" alt="great image">
  <div class="comment"></div>
</template>
Run Code Online (Sandbox Code Playgroud)

然而,“模板”一词意味着您不会按原样复制粘贴,未经修改。模板意味着您要使用特定值更新某些变量。它建议使用以下方法更新节点:

var t = document.querySelector('#mytemplate');
// Populate the src at runtime.
t.content.querySelector('img').src = 'logo.png';

var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
Run Code Online (Sandbox Code Playgroud)

是不是很完美?有 querySelector 来获取元素,以便您可以更新其属性。我只是不明白他为什么在克隆之前更新模板。但这不是我的问题。真正的问题是,在我的情况下,要更新的变量的位置是未知的。它可以是任何模板结构中的属性或innerText。我相信这是模板最普遍和最常用的用法。所以,我可以确保变量 id 在模板中是唯一的,比如这里的 #reply

<template id="comment-template">
  <li class="comment">
    <div class="comment-author"></div>
    <div class="comment-body"></div>
    <div class="comment-actions">
      <a href="#reply" class="reply">Reply</a>
    </div>
  </li>
</template>
Run Code Online (Sandbox Code Playgroud)

应该更新#reply,但作者没有解释如何做到这一点。我成功地在原始模板上使用了innerHTML,document.querySelector('#mytemplate').innerHTML.replace(id, value)但这破坏了模板供以后使用,如上所述。我未能更新克隆的文本。这可能是因为 template.clone 生成了一个没有 innerHTML 的文档片段。但是,在推动之前,我决定研究替代方案,因为我知道 innerHTML/outerHTML 不是很标准。

替代innerHTML?检查innerHTML的替代方案,但同样,他们对模板假设太多。他们不是仅仅用用户值替换一些特定的标识符,而是完全重新创建模板,这违背了模板的整个概念。一旦您在变量评估中重新创建其整个代码,模板就会失去任何意义。那么,<template>应该怎么用呢?

Mou*_*ser 2

再次使用<template>.querySelectorAll选择元素并setAttribute更改href

 var a = <template>.querySelectorAll("a[href='#reply']");
 a[0].setAttribute("href", <url>)
Run Code Online (Sandbox Code Playgroud)

这是一个更通用的函数。它更改克隆模板中所选元素的属性,当然这是非常基本的,

    //object = the cloned template.
    //selector = the selector argument which selects all nodes.
    //attribute = the attribute to change.
    //value = the value that needs to be set to the attribute.

function changeTemplateValues(object, selector, attribute, value)
{
    elements = object.querySelectorAll(selector);
    if (elements.length == 0)
    {
        return false; //stop executing. No elements were found.
    }
    else if (!attribute && !value)
    {
        return elements; //no attributes and values are set, return nodelist;
    }
    else
    {
        if (attribute)
        {
            //loop over all selected elements to change them.
            for (var i = 0; i < elements.length; ++i)
            {
                if (attribute.match(/innerHTML|textContent|text|nodeValue/g) )
                {
                    elements[i][attribute] = value;
                }
                else
                {
                    elements[i].setAttribute(attribute, value);
                }
            }
        }
        else
        {
            //No attribute return false;
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)