【问题标题】:how to tell if a property exists and is false如何判断属性是否存在且为假
【发布时间】:2011-04-23 12:46:17
【问题描述】:

我很难确定传入 jquery 模板的数据是否存在并且是否为假而不会出错。这是我用来测试的

<html>
<head>
<title>jQuery Templates {{if}} logic</title>
</head>
<body>

<p id="results"></p>
<p>How do you test if the Value exists and is false?</p>

<script id="testTemplate" type="text/html">

    Test ${Test}:

    {{if Value}}
        Value exists and is true
    {{else}}
        Value doesn't exist or is false
    {{/if}}

    <br/>

</script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.tmpl.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#testTemplate").tmpl({Test:1}).appendTo("#results");
        $("#testTemplate").tmpl({Test:2, Value:true}).appendTo("#results");
        $("#testTemplate").tmpl({Test:3, Value:false}).appendTo("#results");
    });
</script>

</body></html>

有人知道怎么做吗?

【问题讨论】:

    标签: javascript jquery templates jquery-templates


    【解决方案1】:

    您可以使用=== false 检查在其中使用另一个else 语句,如下所示:

    {{if Value}}
        Value exists and is true
    {{else typeof(Value) != "undefined" && Value === false}}
        Value exists and is false
    {{else}}
        Value doesn't exist or isn't explicitly false
    {{/if}}
    

    You can test it out heretypeof 检查是因为您将收到 Value is not defined 错误 only Value === false。您还可以添加其他检查,例如,如果未指定值,{{else typeof(Value) == "undefined"}} 将为真。

    【讨论】:

      【解决方案2】:

      你可以写一个函数来帮你检查:

      $(document).ready(function() {
          function isExplicitlyFalse(f) { return f === false; }
      
          $("#testTemplate").tmpl({Test:1, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
          $("#testTemplate").tmpl({Test:2, Value:true, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
          $("#testTemplate").tmpl({Test:3, Value:false, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
      });
      

      然后在您的模板中:

      {{if item.isExplicitlyFalse(Value)}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 2012-01-05
        相关资源
        最近更新 更多