lundi 17 août 2020

How to include an if statement within the javascript of a multiple line innerHTML property?

I am using java-script to render a dynamic svg based on js variables on my html/php page using the innerHTML property.

It's a complex svg so I have split the string into multiple lines.

My current code works fine;

document.getElementById('diagram1').innerHTML 
= '<svg width="'+canvas_width+'" height="'+canvas_height+'">'
+ '<line x1="0" y1="'+depth+'" x2="'+width+'" y2="'+depth+'" stroke="#ff6622" stroke-width="3"></line>'
+ '<rect width="'+svg_width+'" height="'+svg_height+'" x="100" y="140" fill="#CCC"></rect>'
+ '</svg>';

However, if I wrap any of the lines in an if statement then that line is never rendered even if the conditions of the if statement are met.

document.getElementById('diagram1').innerHTML 
= '<svg width="'+canvas_width+'" height="'+canvas_height+'">'
if (test == 'on') {
+ '<line x1="0" y1="'+depth+'" x2="'+width+'" y2="'+depth+'" stroke="#ff6622" stroke-width="3"></line>'
}
+ '<rect width="'+svg_width+'" height="'+svg_height+'" x="100" y="140" fill="#CCC"></rect>'
+ '</svg>';

Is there a different / better way to do this? Am I missing something?

Aucun commentaire:

Enregistrer un commentaire