将字符串转换为 link javascript 用于小胡子模板的对象

Convert string into link javascript object used for mustache template

我有一个对象,它有一个 属性,值为字符串。

var notificationDetails = {
  dangerMessage: "I love basketball and love to watch it in. <a href='www.nba.com'>Link</a>;",
  seats: "1 seatRemaining",
  pName: "Item 1",
  class: ""
};

document.write(notificationDetails.dangerMessage);

如何将 dangerMessage 属性 中的 a 元素转换为 link,它读作字符串而不是实际的 link。提前谢谢你。

我忘了说我正在使用 mustache.js 在对象中渲染 属性 它看起来像这样

<script type="text/x-mustache-tmpl" id="order-template">
     <div>{{dangerMessage}} </div>
</script>

有效。

查看下面代码片段的结果。

var notificationDetails = {
  dangerMessage: "I love basketball and love to watch it in. <a href='www.nba.com'>Link</a>;",
  seats: "1 seatRemaining",
  pName: "Item 1",
  class: ""
};

document.write(notificationDetails.dangerMessage);

编辑 mustache.js: 未转义 html 你只需要使用 三重 括号 {{{ }}} 而不是双括号 {{ }}转义 html:

<div>{{{dangerMessage}}}</div>

Docs

您可以使用 .innerHtml属性 个元素,共 DOM 个:

function myFunction() {
  var notificationDetails = {
           dangerMessage: "I love basketball and love to watch it in. <a href='www.nba.com'>Link</a>;",
           seats: "1 seatRemaining",
           pName:  "Item 1",
           class:""
     };
    document.getElementById("demo").innerHTML = notificationDetails.dangerMessage;
}
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>

查看此页面:https://jsfiddle.net/o8nzwxt1/

从评论中可以使用{{{dangerMessage}}}:

<script type="text/x-mustache-tmpl" id="order-template">
  <div>{{{dangerMessage}}}</div>
</script>

来自Doc

All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.