为了账号安全,请及时绑定邮箱和手机立即绑定

如何在不使用任何库的情况下在一组所有匹配元素中显示双大括号之间的数据?

如何在不使用任何库的情况下在一组所有匹配元素中显示双大括号之间的数据?

慕雪6442864 2021-11-18 16:08:15
我想做一个可以做这样的事情的函数:HTML : <h1 class="demo">I am {{ name }}</h1> <span class="demo">{{ name }} learn JavaScript</span>JS:data(".demo", {   name: "Arc"};输出 : I am Arc Arc learn JavaScript可以制作可以做到这一点的 data() 函数吗?我不想为了使用这个函数而使用任何外部库!
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

使用正则表达式{{ .. }}将 HTML 中的 s替换为传递对象中的适当值(如果有):


const data = (selector, obj) => {

  document.querySelectorAll(selector).forEach((elm) => {

    elm.textContent = elm.textContent.replace(

      /{{ *(\w+) *}}/g,

      // If key is in the obj, replace with the value

      // otherwise, replace with the match (make no changes):

      (match, key) => key in obj ? obj[key] : match

    );

  });

};


data(".demo", {

   name: "Arc"

});

 <h1 class="demo">I am {{ name }}</h1>

 <span class="demo">{{ name }} learn JavaScript</span>


如果您还需要考虑嵌套元素,则选择父级的所有文本节点,并执行相同的操作:


const getTextNodes = (parent) => {

    // https://stackoverflow.com/questions/2579666/getelementsbytagname-equivalent-for-textnodes

    var walker = document.createTreeWalker(

        parent, 

        NodeFilter.SHOW_TEXT, 

        null, 

        false

    );


    var node;

    var textNodes = [];


    while(node = walker.nextNode()) {

        textNodes.push(node);

    }

    return textNodes;

}


const data = (selector, obj) => {

  document.querySelectorAll(selector).forEach((elm) => {

    getTextNodes(elm).forEach((node) => {

      node.textContent = node.textContent.replace(

        /{{ *(\w+) *}}/g,

        // If key is in the obj, replace with the value

        // otherwise, replace with the match (make no changes):

        (match, key) => key in obj ? obj[key] : match

      );

    });

  });

};


data(".demo", {

   name: "Arc"

});

span > span {

  background-color: yellow;

}

<h1 class="demo">I am {{ name }}</h1>

 <span class="demo">{{ name }} learn JavaScript <span> nested {{ name }} </span></span>



查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信