如何判断属性是否存在且是否为假

Rus*_*sby 7 javascript jquery templates jquery-templates

我很难确定传入jquery模板的数据是否存在,并且在没有出错的情况下为false.这是我用来测试的

<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>
Run Code Online (Sandbox Code Playgroud)

有谁知道怎么做?

Nic*_*ver 8

你可以使用支票else在那里使用另一个语句=== false,如下所示:

{{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}}
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下.该typeof检查是因为你会得到一个Value is not defined错误与唯一 Value === false.您还可以添加其他检查,例如{{else typeof(Value) == "undefined"}},如果未指定值,则为true.