【问题标题】:Knockout binding error敲除绑定错误
【发布时间】:2015-05-26 10:17:54
【问题描述】:

所以我有这个加载 Instagram 数据的画廊,有时 Instagram 照片没有带有标题,这就是它中断的时候,所以最合乎逻辑的做法是检查标题是否存在但它仍然会中断.

Live example

<!-- ko if: $root.entries().length != 0 -->
        <!-- ko foreach: $root.entries() -->
            <!-- ko with: $root.entries()[$index()] -->
                <span data-bind="logger: typeof caption"></span>
                <figure>
                    <img src="" data-bind="attr: {src: images.low_resolution.url}"/>
                    <figcaption>
                            <a target="_blank" data-bind="text: user.username, attr: {href: 'http://instagram.com/' + user.username }"></a>
                         <!--ko if: typeof caption != 'null'-->
                            <span>
                                <!-- ko text: caption.text --><!-- /ko -->
                            </span>

                         <!--/ko-->
                    </figcaption>
                </figure>
            <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->

【问题讨论】:

  • 您应该能够在 span 标签中同时拥有 if 绑定和标题文本绑定,而不是使用 ko 伪标签。此外,不需要检查 root.entries 长度; foreach 正确处理零情况。

标签: javascript text knockout.js binding instagram


【解决方案1】:

typeof 运算符不返回null,因此您的条件实际上是无条件的:即使caption 为空,它也总是尝试渲染caption.text

你可以试试:

<!--ko if: caption-->

如果caption 是“真实的”(不是falsenullundefined、0、空字符串等),这将扩展评论模板的内容

【讨论】:

    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2015-11-14
    • 2012-06-25
    • 2015-12-06
    • 1970-01-01
    • 2014-06-27
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多