简体   繁体   English

IE 8的条件注释不起作用

[英]Conditional comment for IE 8 not working

I'm trying to change the SRC attribute of my iFrame for users on IE 8 or less. 我正在尝试为IE 8或更低版本的用户更改iFrame的SRC属性。

Here's my code : 这是我的代码:

  <script>
var i_am_old_ie = false;
<!--[if lte IE 8]>
i_am_old_ie = true;
<![endif]-->
</script>
    <script type="text/javascript">
    $(document).ready(function() {
if(i_am_old_ie) {
   $("#shop").attr("src","shopping_cart/browser_support.html"); 
} else {
    $("#shop").attr("src","shopping_cart/index.html"); 
}      
});
</script>

It detects that it's IE...but still sends all IE users to shopping_cart/browser_support.html . 它检测到它是IE ...,但仍将所有IE用户发送到shopping_cart/browser_support.html Even if I use IE 9, it will send me there. 即使我使用IE 9,它也会将我发送到那里。 Same thing for 7, or 8. 7或8同样。

But it sends all other users not using IE to shopping_cart/index.html (wich is correct). 但这会将所有未使用IE的所有其他用户发送到shopping_cart/index.html (正确)。

What's wrong in my code? 我的代码有什么问题?

Thank you! 谢谢!

You can't insert the inside the script tag. 您不能在script标记内插入。 It needs to be outside. 它必须在外面。

<script>
var i_am_old_ie = false;
</script>

<!--[if lte IE 8]>

<script>
i_am_old_ie = true;
</script>
<![endif]-->

As others mentioned you can not use HTML conditional statements between <script> tags. 就像其他人提到的那样,您不能在<script>标记之间使用HTML条件语句。

This should work however: 但是,这应该起作用:

if (document.all && !document.getElementsByClassName) {
    i_am_old_ie = true;
}

The above will only run in IE8 or below 以上仅在IE8或更低版本中运行

Edit: 编辑:

Some nice examples LINK 一些不错的例子LINK

There is a different syntax for conditional comments inside JavaScript. JavaScript中的条件注释有不同的语法。 What does @cc_on mean in JavaScript? @cc_on在JavaScript中是什么意思? has details. 有详细信息。

Wikipedia's Conditional comment page has an example of version switching using it. Wikipedia的“条件注释”页面上有一个使用它进行版本切换的示例。

 <script> /*@cc_on @if (@_jscript_version == 10) document.write("You are using IE10"); @elif (@_jscript_version == 9) document.write("You are using IE9"); @elif (@_jscript_version == 5.8) document.write("You are using IE8"); @elif (@_jscript_version == 5.7 && window.XMLHttpRequest) document.write("You are using IE7"); @elif (@_jscript_version == 5.6 || (@_jscript_version == 5.7 && !window.XMLHttpRequest)) document.write("You are using IE6"); @elif (@_jscript_version == 5.5) document.write("You are using IE5.5"); @else document.write("You are using IE5 or older"); @end @*/ </script> 

Conditional HTML comments only work in HTML. 条件HTML注释仅适用于HTML。

JavaScript is not HTML. JavaScript不是HTML。

It's generally not a good idea, and feature detection is reccomended, but if using jQuery you can do: 通常这不是一个好主意,建议使用功能检测,但是如果使用jQuery,则可以执行以下操作:

var i_am_old_ie = $.browser.msie && ($.browser.version <= 8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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