我有一个类似于下面的代码,我想以不同的方式呈现资本与cityName Barnsley ,不同的是一个具有其他名称的城市。 if binding 的正确方法是什么?我是否必须将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>
Ok还是没有成功我的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>
非常感谢任何帮助!
答案 0 :(得分:0)
你几乎就在那里,如果它不会在以后改变,它不必是可观察的,你可以做if语句和渲染不同,如下所示
<ul data-bind="foreach: planets">
<li>
Planet: <b data-bind="text: name"> </b>
<div data-bind="if: capital">
<!-- ko if:capital.cityName=='Barnsley' -->
Capital: <b data-bind="text: capital.cityName"> </b>
<!-- /ko -->
<!-- ko if:capital.cityName=='asdad' -->
Capital: <i data-bind="text: capital.cityName"> </b>
<!-- /ko -->
</div>
</li>
</ul>
答案 1 :(得分:0)
不,它不必是一个可观察的(只要它之后不会被改变;如果确实如此,更改将不会自动反映在视图中),并且你提出的绑定几乎是正确的:它应该是data-bind="if: cityName=='Barnsley'"
(注意冒号和引号)。