0

我有一个类似于下面的代码,我想用 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>

任何帮助都感激不尽!

4

2 回答 2

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>

或者你也可以做 switch case https://github.com/mbest/knockout-switch-case

于 2013-10-07T16:54:32.573 回答
0

不,它不必是可观察的(只要它之后没有被更改;如果是,更改不会自动反映在视图中),并且您提出的绑定几乎是正确的:它应该be data-bind="if: cityName=='Barnsley'"(注意冒号和引号)。

于 2013-10-07T16:57:37.910 回答