Jquery if div doesn't exist
I'm using 1 js for 2 different pages. 1 page doesn't have a div which the开发者_如何转开发 other does. So when I submit the values, I get a $(
js error
for
$('.description'+save_id+'').html(description_val).show(); //update category description
I suspect that I get the error because there is nothing to show(). Is there a short code I can use to detect if the div.description exists otherwise don't do the function?
jQuery will not error if it has nothing to perform on. The show()
would not be a problem. To answer your question, though, you can check the length
property on the jQuery object returned from $
.
If the description_val
variable is undefined
, then the code will fail.
Try using an if()
statement to only run the code if description_val
is not undefined
.
if(description_val) {
$('.description'+save_id+'').html(description_val).show();
}
Or if for some reason the value of description_val
may be a value that would equate to false
, then do this:
if(description_val !== undefined) {
$('.description'+save_id+'').html(description_val).show();
}
From what you posted I'd check to make sure the variables you're using are all defined at this stage. To check for existence you can do this:
if ($('.description' + save_id).size() > 0) {
// code here that operates on the div.
}
This is essentially just a syntactic alternative to checking the length property.
精彩评论