knockout “if binding” not working

2020-07-06 04:26发布

When debugging with Chrome, I can see CoverPrices has 9 elements. The foreach loop actually works well and the table looks correct with the first span being bound to Item1 correctly.

However, the if binding does not work and both images are displayed. Yet, all the elements in Item2 have the true value, so only the first image should show up.

<!-- ko foreach: CoverPrices -->
    <tr>
        <td>
            <span data-bind="text: Item1"></span>
        </td>
        <!-- ko foreach: Item2 -->
        <td>
            <img src="~/Images/yes.png" alt="oui" data-bind="if: $data" /> 
            <img src="~/Images/no.png" alt="non" data-bind="ifnot: $data" /> 
        </td>
        <!-- /ko -->
    </tr>
    <!-- /ko -->

Is there something wrong with my binding ?

2条回答
甜甜的少女心
2楼-- · 2020-07-06 05:17

Image is not binding to DOM, but the image is loading. You can check in Network traffic. It should not load when if bind is used

查看更多
虎瘦雄心在
3楼-- · 2020-07-06 05:24

The if-binding does not affect the whole element, but its content. And because an img element does not have content, the binding does not matter.

This will work, with span as container elements:

<span data-bind="if: $data"><img src="~/Images/yes.png" alt="oui" /></span>
<span data-bind="ifnot: $data"><img src="~/Images/no.png" alt="non" /></span>

There is also a container-less syntax, if you don't want the additional elements:

<!-- ko if: $data -->
    <img src="~/Images/yes.png" alt="oui" />
<!-- /ko -->
<!-- ko ifnot: $data -->
    <img src="~/Images/no.png" alt="non" />
<!-- /ko -->
查看更多
登录 后发表回答