2010-10-10 23 views
6

मुझे यह निर्धारित करने में कठिनाई हो रही है कि 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> 

परीक्षण करने के लिए उपयोग कर रहा हूं क्या कोई जानता है कि यह कैसे करें?

उत्तर

6

आप एक === false जांच का उपयोग कर, इस तरह में एक और else कथन का उपयोग कर सकते हैं::

$(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 heretypeof चेक इसलिए है क्योंकि आपको त्रुटि त्रुटिValue === false के साथ त्रुटि मिलेगी। आप अन्य चेक भी जोड़ देंगे, उदाहरण के लिए {{else typeof(Value) == "undefined"}} सत्य होगा यदि मान निर्दिष्ट नहीं किया गया था।

+0

यह सुंदर नहीं दिखता है लेकिन यह काम करता है, धन्यवाद! –

1

आप आप के लिए जाँच करने के लिए एक समारोह लिख सकते हैं:

{{if item.isExplicitlyFalse(Value)}} 
संबंधित मुद्दे