how to tell if a property exists and is false

三世轮回 提交于 2019-12-09 12:29:32

问题


I am having a hard time determining if data passed into the jquery template exists and is false without getting errors. This is what I am using to test

<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>

Does anyone know how to do it?


回答1:


You can use another else statement in there using a === false check, like this:

{{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 here. The typeof check is because you'll get a Value is not defined error with only Value === false. You would add other checks as well, for example {{else typeof(Value) == "undefined"}} would be true if the value wasn't specified.




回答2:


You could write a function to check for you:

$(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");
});

then in your template:

{{if item.isExplicitlyFalse(Value)}}


来源:https://stackoverflow.com/questions/3901641/how-to-tell-if-a-property-exists-and-is-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!