如何判断一个属性是否存在并且是假的
问题描述:
我很难确定是否存在传入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>
有谁知道该怎么做?
答
您可以使用另一种else
声明中有使用=== false
检查,像这样:
$(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 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。 typeof
检查是因为你会得到一个Value is not defined
错误只有Value === false
。您也可以添加其他检查,例如{{else typeof(Value) == "undefined"}}
如果未指定值,则会为真。
答
你可以写一个函数来检查你:
{{if item.isExplicitlyFalse(Value)}}
它看起来不漂亮,但它的工作原理,谢谢! – 2010-10-10 22:51:37