如何判断属性是否存在且是否为假 [英] how to tell if a property exists and is false

查看:81
本文介绍了如何判断属性是否存在且是否为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < html> 
< head>
< title> jQuery模板{{if}}逻辑< / title>
< / head>
< body>

< p id =results>< / p>
< p>如何测试Value是否存在且为false?< / p>

< script id =testTemplatetype =text / html>

测试$ {测试}:

{{如果值}}
值存在且为真
{{else}}
价值不存在或为假
{{/ if}}

< br />

< / script>

< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js>< ; /脚本>
< script type =text / javascriptsrc =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>

有谁知道怎么做?

=== false 检查,如下所示:

  {{if Value}} 
值存在且为真
{{else typeof(Value)!=undefined&&值=== false}}
值存在且为false
{{else}}
值不存在或未明确错误
{{/ if}}

你可以在这里测试一下 typeof 检查是因为您将获得未定义值错误 值=== false 。您还可以添加其他检查,例如 {{else typeof(Value)==undefined}} 如果未指定值,则为true。


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?

解决方案

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.

这篇关于如何判断属性是否存在且是否为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆