使用容器内的Knockout绑定多个span标签,仅呈现第一个元素 [英] Binding multiple span tags with Knockout inside a container only rendering the first element
本文介绍了使用容器内的Knockout绑定多个span标签,仅呈现第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出此剔除javascript:
Given this knockout javascript:
function TestModel(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
}
function TestView() {
this.TestList= ko.observableArray([]);
this.TestList([{Id: 1, Name: 'One'},{Id: 2, Name: 'Two'}]);
}
ko.applyBindings(new TestView());
这个HTML:
<div data-bind='foreach: TestList'>
<p>
<span data-bind="text: Id" />
<span data-bind="text: Name" />
</p>
</div>
我希望它能像这样渲染:
I would expect it to render like this:
<div>
<p>
<span>1</span>
<span>One</span>
</p>
<p>
<span>2</span>
<span>Two</span>
</p>
</div>
但是它看起来像这样:
<div>
<p>
<span>1</span>
</p>
<p>
<span>2</span>
</p>
</div>
如果我更改HTML以便每个span
都位于其自己的p
标记中,则会同时渲染它们.
If I change the Html so that each span
is in it's own p
tag, it does render them both.
<div data-bind='foreach: TestList'>
<p>
<span data-bind="text: Id" />
</p>
<p>
<span data-bind="text: Name" />
</p>
</div>
此外,如果我放下span标签并使用comment语法,它将使两个绑定都很好:
Also, if I drop the span tags and use the comment syntax it renders both bindings just fine:
<div data-bind='foreach: TestList'>
<p>
<!--ko text: Id--><!--/ko-->
<!--ko text: Name--><!--/ko-->
</p>
</div>
为什么在第一个示例中第二个span
标签没有显示?
Why is the second span
tag not rendering in the first example?
推荐答案
更改此内容:
<span data-bind="text: Id" />
对此:
<span data-bind="text: Id"></span>
根据我的经验,当您没有结束标签时,KO不喜欢它.
In my experience, KO doesn't like it when you don't have a closing tag.
这篇关于使用容器内的Knockout绑定多个span标签,仅呈现第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文