2010-10-10 16 views
6

Ho difficoltà a determinare se i dati passati nel modello jQuery esistono e sono falsi senza ottenere errori. Questo è quello che sto usando per testarecome sapere se una proprietà esiste ed è falsa

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

Qualcuno sa come farlo?

risposta

6

È possibile utilizzare un altro else dichiarazione in là con un assegno === false, in questo modo:

{{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. Il controllo typeof è perché si otterrà un errore Value is not defined con soloValue === false. Aggiungerei anche altri controlli, ad esempio {{else typeof(Value) == "undefined"}} sarebbe vero se il valore non è stato specificato.

+0

non sembra carino ma funziona, grazie! –

1

Si potrebbe scrivere una funzione per controllare per voi:

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

poi nel modello:

{{if item.isExplicitlyFalse(Value)}} 
Problemi correlati