0

I'm passing some variables to my google maps scrip to output an address in an info window. The variables are being pulled from a database, but not all of them will always exist. Using the following code I sometimes end up with multiple <br> tags in a row, meaning I get awkward breaks in the content.

So my question is how do I make it conditional so that only the variables that exist will display, followed by a <br>?

var contentString = '<div id="map_info">'+
                    '<h4>' + gmapsstring.gmapaddressname + '</h4>'+
                    '<div id="bodyContent">'+
                    '<p>' + gmapsstring.gmapaddressstreet + '<br>' +
                    gmapsstring.gmapaddressline2 + '<br>' +
                    gmapsstring.gmapaddressline3 + '<br>' +
                    '<span class="gmap_postcode">' + gmapsstring.gmapaddresspostcode + '</span></p>'+
                    '</div>';

Any suggestions would be greatly appreciated.

Thanks

4

1 回答 1

0

你可以使用length变量的属性,所以你会有类似的东西:

var contentString = '<div id="map_info">';
if( gmapsstring.gmapaddressname.length > 0 ) {
   contentString += '<h4>' + gmapsstring.gmapaddressname + '</h4>';
}

等等。或者更好的是,您可以使用类似的代码遍历属性。

于 2013-07-29T18:17:50.213 回答