Apply conditional statements within string output in JavaScript
I'm using a jQuery plugin named "jParse" to parse an XML file like so:
$('#content').jParse({
ajaxOpts: {url: 'data.xml'},
elementTag: ['title', 'description'],
output: '<h2>jpet0</h2><p>jpet1</p>'
});
As you can see, the "jpet" variables correlate with the elementTag array.
How would I check to see if the jpet var contains data (as some of the tags in the XML are empty) and withhold the HTML tags if it doesn't?
This doesn'开发者_如何学Got work:
$('#content').jParse({
ajaxOpts: {url: 'data.xml'},
elementTag: ['title', 'description', 'extra'],
output: if (jpet0) { '<h2>jpet0</h2>' } + '<p>jpet1</p><p>jpet2</p>'
});
But it does give a good idea of what I'm trying to achieve.
Thanks in advance!
This should work, if I understood the docs correctly:
$('#content').jParse({
ajaxOpts: {url: 'data.xml'},
elementTag: [
{elem:'title', format: function(title){
if(title != '') return '<h2>' + title + '</h2>';
else return '';
}}, 'description'],
output: 'jpet0<p>jpet1</p>'
});
You could use the ternary operator:
output: (jpet0 ? '<h2>jpet0</h2>' : '') + '<p>jpet1</p><p>jpet2</p>'
But what's wrong with just putting the HTML string in a variable and then prepending the additional HTML using a regular if
statement?
It seems jParse doesn't support that kind of template (judged from usage page; may be wrong). One possible solution then would be post-process the result, like this:
$('#content').remove('h2:empty');
// i.e. removes all empty H2 elements from #content.
Of course you have to ensure that there is no other places empty H2 elements appear.
精彩评论