简体   繁体   English

如何使用数据绑定if语句确定某项是否等于字符串中的文本?

[英]How to have a data-bind if statement for if something is equal to text in a string?

I need to execute code if a certain value is equal to a string (the string is 'stories'). 如果某个值等于字符串(字符串为“故事”),则需要执行代码。

I have: 我有:

<!-- data-bind if: header.current_collection.url_type == 'stories' -->
    <p>text</p>
<!-- /data-bind -->

But it's always false. 但这总是错误的。 I put <p data-bind="text: header.current_collection.url_type"></p> under it to be sure the value was 'stories' and it displays 'stories' onto the page so I know the value is right. 我将<p data-bind="text: header.current_collection.url_type"></p>放在其下,以确保该值是“故事”,并且在页面上显示“故事”,因此我知道该值是正确的。

Why is this being executed as false when it's true. 为什么当它为true时将其执行为false。 Is there a syntax problem here? 这里有语法问题吗?

您是否尝试过使用严格等式 '==='而不是'=='?

Firstly, I agree with the previous answer that you should be using the strict equality operator. 首先,我同意前面的答案,即您应该使用严格相等运算符。 Secondly, you are using incorrect syntax - where you have data-bind should be ko, ie: 其次,您使用的语法不正确-您具有数据绑定的位置应为ko,即:

<!-- ko if: header.current_collection.url_type === 'stories' -->
    <p>text</p>
<!-- /ko -->

You can find the knockout if binding docs here 如果在这里绑定文档,则可以找到淘汰赛

Adrian answered this in a comment. 阿德里安在评论中回答了这个问题。 You are comparing the observable itself rather than the value. 您正在比较可观察对象本身而不是值。 Change it to: 更改为:

if: header.current_collection.url_type() == 'stories'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM