简体   繁体   English

替换dom元素中的占位符

[英]Replace placeholders in dom element

Given a dome element like this: 给定这样一个圆顶元素:

<div>
    <ul>
        {{placeholder|value1}}
    </ul>
    <a href="{{placeholder|value2}}">{{placeholder|value3}}</a>
</div>

and a json string containing the values: 和一个包含值的json字符串:

var placeholder = {"values": {"value1" : "<li>hello</li>", "value2" : "#", "value3": "hello again"}}

what would be the correct way to replace the values in the dom element in a generalised way ie the example above is only for illustration and the placeholder|value can appear anywhere in the element. 用通用的方式替换dom元素中值的正确方法是什么,即,上面的示例仅用于说明,而占位符|可以出现在元素中的任何位置。

js fiddle: http://jsfiddle.net/8RPkY/ js小提琴: http//jsfiddle.net/8RPkY/

Normally, I'd drop in some code to recursively iterate through all DOM nodes: 通常,我会放入一些代码以递归地遍历所有DOM节点:

  • If it's an Element, then iterate through its Attributes and replace placeholders, then recurse 如果它是元素,则遍历其属性并替换占位符,然后递归
  • If it's a Text node, replace placeholders in its contents 如果是文本节点,请在其内容中替换占位符

Buuuuut... in this case you may just be better off nuking it with a regex: Buuuuut ...在这种情况下,您最好使用正则表达式对其进行修改:

output = input.replace(/\{\{placeholder\|(.*?)\}\}/g,function(_,k) {
     return placeholder[k] || _;
});

In this particular case, it's okay to parse HTML with regex because... well, the regex itself has nothing to do with HTML and does not affect the underlying HTML in any way. 在这种特殊情况下,可以使用正则表达式解析HTML,因为...好吧,正则表达式本身与HTML无关,并且不会以任何方式影响基础HTML。

Demo: http://jsfiddle.net/8RPkY/2/ 演示: http : //jsfiddle.net/8RPkY/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM