用嵌套的html元素敲出绑定

时间:2014-03-31 12:14:47

标签: javascript knockout.js

使用嵌套的html元素时,我遇到了一些敲除绑定问题

<ul class="result-list" data-bind="foreach: newsData">
    <li>
        <a class="big-link" data-bind="text: Title, attr: { href: Url }"></a>
        <div data-bind="html: Content"></div>
        <div class="meta" data-bind="text: PublishDate">
            <span class="time" data-bind="text: PublishTime"></span>
            <span class="changed" data-bind="text: ChangedDate, visible: IsChanged">
                <span class="time" data-bind="text: ChangedTime"></span>
            </span>
        </div>
    </li>
</ul>

json

var sample = [{
    "Id": 80055,
    "Title": "Not changed!",
    "Content": "<p>Curabitur eget euismod mi. Cras mollis augue a massa porttitor posuere. Quisque tempus justo vel orci venenatis lobortis.</p>",
    "Url": "/asd/Not-changed/",
    "PublishDate": "28. mars 2014",
    "PublishTime": "Kl 01:30",
    "IsChanged": false,
    "ChangedDate": "28. mars 2014",
    "ChangedTime": "Kl 01:30"
}, {
    "Id": 80046,
    "Title": "Ny artikkel",
    "Content": "<p>This is content</p>\n<p>Demo</p>",
    "Url": "/asd/Ny-artikkel/",
    "PublishDate": "4. mars 2014",
    "PublishTime": "Kl 12:00",
    "IsChanged": true,
    "ChangedDate": "24. mars 2014",
    "ChangedTime": "Kl 04:47"
}];

它很好地绑定到PublishDate但似乎覆盖了所有子元素。任何建议如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

Knockout docs读取文本绑定:

  

Knockout使用您的参数将元素的内容设置为文本节点   值。 之前的所有内容都将被覆盖

您可能需要编写子元素来容纳这些数据绑定:

<ul class="result-list" data-bind="foreach: newsData">
    <li>
        <a class="big-link" data-bind="text: Title, attr: { href: Url }"></a>
        <div data-bind="html: Content"></div>
        <div class="meta">
            <span data-bind="text: PublishDate"></span>
            <span class="time" data-bind="text: PublishTime"></span>
            <span class="changed">
                <span data-bind="text: ChangedDate, visible: IsChanged"></span>
                <span class="time" data-bind="text: ChangedTime"></span>
            </span>
        </div>
    </li>
</ul>