简体   繁体   中英

How can I embed a conditional comment for IE with innerHTML?

Ok so I want to conditionally add this line of code;

<!--[if ! IE]> <embed src="logo.svg" type="image/svg+xml" /> <![endif]-->

Using:

document.getElementById("logo") .innerHTML='...';

In a if()/else() statement and it don't write it! If i get rid of the selective comment ( <!--[if ! IE]><![endif]--> ) and only put the SVG ( <embed src="logo.svg" type="image/svg+xml" /> ) it work! what should I do?

I found a way around but i think in the Android browser the thing will pop up twice.

here's what I've done ( and its Validated stuff!);

<!DOCTYPE html>
<html>
<head>
<META CHARSET="UTF-8">
<title>SVG Test</title>
<script type="text/javascript">
//<![CDATA[
onload=function()
    {

        var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {

        document.getElementById("logo").innerHTML='<img src="fin_palais.png"/>';

        }


    }
//]]>

</script>
</head>
<body>

    <div id="logo">
        <!--[if lt IE 9]>
            <img src="fin_palais.png"/>
        <![endif]-->

        <!--[if gte IE 9]><!-->

            <embed src="fin_palais.svg" type="image/svg+xml" />

        <!--<![endif]-->

    </div>

</body>

It's probably better to not put it in the innerHTML, but use the condition to control whether it goes in the innerHTML or not like this:

var str = '...';    // whatever your other HTML is
<!--[if ! IE]>
str += '<embed src="logo.svg" type="image/svg+xml" />';
<![endif]-->

If you show us the whole problem you're trying to solve, there are probably ways to do this without browser conditionals.

Your syntax for detecting not IE is broken.

Microsoft recommended way - results in bad markup

<![if !IE]>
 <p>This is shown in downlevel browsers, but is invalid HTML!</p>
<![endif]>

This way shows works too and is valid markup

<!--[if !IE]>-->
  <p>This is shown in downlevel browsers.</p>
<!--<![endif]-->

That said, @jfriend00's comment is good.

Your way begins an html comment which is never closed, and thus doesn't process correctly. html comments are opened with the first -- and closed with the second. They don't close with the > like regular elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM