如何将 HTML 添加到此 Knockout.js Viewmodel 变量?
How can I add HTML to this Knockout.js Viewmodel variable?
我在页面上显示了一个步骤列表。一些步骤(但不是全部)将有 1-3 个子步骤。我在想最简单的方法就是在视图模型的每个步骤声明中手动编写 HTML。
如果你看下面的代码,我想做的是这样的:
this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2 <ul><li>substep 1</li><li>substep2</li></ul>");
问题是,HTML 被解释为 string
而不是 HTML
。我怎样才能让它将 HTML 解释为实际的 HTML?
Fiddle: https://jsfiddle.net/8o31m6rq/2/
HTML:
<ul>
<sidebar-step params="vm: sidebarStepModel0"></sidebar-step>
<sidebar-step params="vm: sidebarStepModel1"></sidebar-step>
<sidebar-step params="vm: sidebarStepModel2"></sidebar-step>
</ul>
JavaScript/Knockout:
//custom element <sidebar-step>
ko.components.register("sidebar-step", {
synchronous: true,
viewModel: function (params) {
this.vm = params.vm;
},
template: "<li data-bind='text: vm.message'>vm.onChangeElement</li>"
});
// model
var SidebarStepModel = function () {
this.message = ko.observable("step description");
};
// viewmodel
var OrderGuideViewModel = function () {
this.sidebarStepModel0 = new SidebarStepModel();
this.sidebarStepModel0.message("step 1");
this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2");
this.sidebarStepModel2 = new SidebarStepModel();
this.sidebarStepModel2.message("step 3");
};
ko.applyBindings(new OrderGuideViewModel());
您只需要使用 html
binding 而不是 text
绑定:
template: "<li data-bind='html: vm.message'>vm.onChangeElement</li>"
我在页面上显示了一个步骤列表。一些步骤(但不是全部)将有 1-3 个子步骤。我在想最简单的方法就是在视图模型的每个步骤声明中手动编写 HTML。
如果你看下面的代码,我想做的是这样的:
this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2 <ul><li>substep 1</li><li>substep2</li></ul>");
问题是,HTML 被解释为 string
而不是 HTML
。我怎样才能让它将 HTML 解释为实际的 HTML?
Fiddle: https://jsfiddle.net/8o31m6rq/2/
HTML:
<ul>
<sidebar-step params="vm: sidebarStepModel0"></sidebar-step>
<sidebar-step params="vm: sidebarStepModel1"></sidebar-step>
<sidebar-step params="vm: sidebarStepModel2"></sidebar-step>
</ul>
JavaScript/Knockout:
//custom element <sidebar-step>
ko.components.register("sidebar-step", {
synchronous: true,
viewModel: function (params) {
this.vm = params.vm;
},
template: "<li data-bind='text: vm.message'>vm.onChangeElement</li>"
});
// model
var SidebarStepModel = function () {
this.message = ko.observable("step description");
};
// viewmodel
var OrderGuideViewModel = function () {
this.sidebarStepModel0 = new SidebarStepModel();
this.sidebarStepModel0.message("step 1");
this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2");
this.sidebarStepModel2 = new SidebarStepModel();
this.sidebarStepModel2.message("step 3");
};
ko.applyBindings(new OrderGuideViewModel());
您只需要使用 html
binding 而不是 text
绑定:
template: "<li data-bind='html: vm.message'>vm.onChangeElement</li>"