我有一个类似于下面的代码,我想用 cityName Barnsley不同地渲染首都,用其他名字不同地渲染一个城市。进行if 绑定的正确方法是什么?我是否必须将 cityName 设置为可观察的才能工作?
<ul data-bind="foreach: planets">
<li>
Planet: <b data-bind="text: name"> </b>
<div data-bind="if: capital">
Capital: <b data-bind="text: capital.cityName"> </b>
</div>
</li>
</ul>
<script>
ko.applyBindings({
planets: [
{ name: 'Mercury', capital: null },
{ name: 'Earth', capital: { cityName: 'Barnsley' } }
]
});
</script>
好的仍然没有成功我的json是这样的:
var Images = {
"ImageInfo": [
{
"thumbs": [
{
"IMAGE": "url(http://...d38508d4f183.jpg)",
"type": "img"
},
{
"IMAGE": "url(http://...d38508d4f183.jpg)",
"type": "video"
}
]
},
{
"thumbs": [
{
"IMAGE": "url(http://...d38508d4f183.jpg)",
"type": "img"
},
{
"IMAGE": "url(http://...d38508d4f183.jpg)",
"type": "video"
}
]
}
]
};
我想要实现的 HTML 如下:
<div id="Images">
<div data-bind="foreach: ViewModelB">
<div data-bind="foreach: thumbs">
<div data-bind="if: type == 'img'">
<a style="width: 50px; height: 50px; float: left; display: block; background-size: cover; margin-left: 15px; cursor: pointer;" data-bind="style: { backgroundImage: IMAGE_PATH }"></a>
</div>
<div data-bind="if: type == 'video'">
<p style="width: 50px; height: 50px; float: left; display: block; background-size: cover; margin-left: 15px; cursor: pointer;" data-bind="style: { backgroundImage: IMAGE_PATH }"></p>
</div>
</div>
</div>
</div>
<script>
var ViewModelB = ko.mapping.fromJS(Images);
ko.applyBindings(ViewModelB, document.getElementById("Images"));
</script>
任何帮助都感激不尽!