我有一個類似於下面的代碼,我想呈現不同的城市名稱巴恩斯利和不同的城市與其他一些名稱資本。 如果綁定,那麼做的正確方法是什麼?我是否必須將cityName設置爲可觀察才能正常工作?Knockout Js渲染與基於Json值的數據綁定不同
<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>
任何幫助將非常感激!
您的代碼有效:http://jsfiddle.net/Rpgnc/ –
我知道上面的代碼是從Knockoutjs文檔複製粘貼的。我的問題是如何使城市名稱巴恩斯利與不同的首都城市名稱:asdad不同。有沒有辦法寫數據綁定:「如果城市名稱==巴恩斯利」呈現以下... –