简体   繁体   English

通过JavaScript传递HTML

[英]Passing HTML through JavaScript

The goal 目标

Pass to the DOM strings with HTML and render it. 用HTML传递到DOM字符串并呈现它。

The scenario 场景

I'm extending properties of an observable (with KnockoutJS) using the follow syntax: 我正在使用以下语法扩展可观察对象的属性(使用KnockoutJS):

self.showDetails.subscribe(function (context) {
    var details = this.showDetails();
    details.nameWithCnpj = context.name() + " <small>" + context.cnpj() + "</small>";
}, this);

If you pay attention on the following line, you can see the HTML on it: 如果您注意以下一行,则可以看到其中的HTML:

details.nameWithCnpj = context.name() + " <small>" + context.cnpj() + "</small>";

When the <small></small> tag arrives on the HTML, it is rendered as string instead of vanilla HTML. <small></small>标记到达HTML时,它将呈现为字符串而不是原始HTML。

The container that houses the nameWithCnpj (using KnockoutJS) is the following: 容纳nameWithCnpj的容器(使用KnockoutJS)如下:

<h2 class="bold float-left" data-bind="text: nameWithCnpj"></h2>

So I ask: How can I teach to JavaScript (or HTML) that the nameWithCnpj variable should be a DOM element instead of a simple string? 所以我问: 我该如何向JavaScript(或HTML)教授nameWithCnpj变量应该是DOM元素而不是简单的字符串?

You need to use the html binding instead of text : 您需要使用html绑定而不是text

The html binding causes the associated DOM element to display the HTML specified by your parameter. html绑定使关联的DOM元素显示您的参数指定的HTML。

Typically this is useful when values in your view model are actually strings of HTML markup that you want to render. 通常,当视图模型中的值实际上是要呈现的HTML标记字符串时,这很有用。

So change your view to: 因此,将您的视图更改为:

<h2 class="bold float-left" data-bind="html: nameWithCnpj"></h2>

If you want to be more MVVM you can create a template which encapsulates your formatting logic and use the template binding: 如果您想成为更多MVVM,则可以创建一个模板,该模板封装格式逻辑并使用template绑定:

<h2 class="bold float-left" 
    data-bind="template: { name: 'nameWithCnpj', data: showDetails}"></h2>

<script id="nameWithCnpj" type="text/html">
   <span data-bind="text: name"></span>
   <small data-bind="text: cpnj"></small>
</script>

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

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