jQuery - check if XML attribute exists
I'm populating an set of <article>
in HTML with either an images or a flash movie depending on the attributes set in an XML like so,
<article image="" flash="flash/1.swf"></article>// this article has flash only
<article image="image/1.jpg" flash=""></article>// this article has image only
There a "n" number of "articles" depending on the XML file. Every article has either an image or a flash movie.
After i load the XML using .ajax()
, i'm using .append()
to add <img>
and <object>
to the article. The problem is, now I have empty tags (img or object) in each article. All articles assigned with images in them have a blank <object>
tag within them and vice versa.
How can I check the XML before appending? So when an article has been assigned an image, the <object>
tag doesn't appear?
The jQuery is as shown below
$('#container')开发者_如何学JAVA.append('<article><img src="'+$image+'"/><object><param name="movie" value="'+$flash+'"></object></article>');
This worked for me
var $flash = $(this).attr('flash');
if ($flash == null) {
...
}
else {
...
}
You should first check if the attribute exists before assigning it to a variable.
if($(this).attr('flash');){
// this attribute exists
// you can also check if its null or not
} else {
// this attribute does NOT exist
}
If order is not important to you you should first filter for the flash attributes, and than for the image attributes. Otherwise something like:
.append('<article>' + ($image != null) ? <img.. : <object..) + "</article>";
精彩评论