Wednesday, March 13, 2013
Basics If-Then Syntax for JS/JQuery
# standard syntax on JS
$(document).ready(function(){
var n = $("#example div").length;
if (n < 2) {
$("body").css("background", "green");
}
else {
$("body").css("background", "orange");
}
});
# this is the shorthand version
var n = $("#example div").length;
$("body").css("background", (n < 2) ? "green" : "orange");
# Checking if selector exists. When you use a selector, jQuery will always return an object. Therefore the if statement will always be true and never be false. So change it to this:
if ($("#mydiv").length > 0) {
// do something here
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.