旧版本IE上的Jquery问题

Jquery issues on older versions of IE

本文关键字:Jquery 问题 上的 IE 版本      更新时间:2023-09-26

我在文档中有以下语句。准备功能:

  if($("sidebar ").html().trim().length == 0)
  {
    $("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>"); 
  };

它在ie9中工作正常,但一旦我选择ie8(浏览器和文档标准),脚本停止工作并给出以下错误:

SCRIPT5007: Unable to get value of the property 'trim': object is null or undefined 
application-e51c9eee7d22e9644481115dc1fedd5f.js, line 7 character 17578

我在调试模式下查看了.js,看到上面的语句被转换为:

$("sidebar ").html().trim().length==0&&$("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>")

如何防止此错误?请注意,我确实看到节点出现在呈现的页面中。

我想也许只是参考shiv5.html可能不足以照顾IE的特质。所以,我通过链轮添加了modernizr.js,并在我的布局中添加了class="no-js"。9.

我错过了什么?我还能做些什么来得到微软老板的青睐呢?

根据MDN, trim在IE <9 .

你可以用$.trim代替:

if($.trim($("sidebar ").html()).length == 0)
{
  $("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>"); 
} // <-- Don't want a semicolon here.

如果您不想找到trim的所有实例并纠正它们,MDN文章列出了另一种选择。如果.trim不是本地可用的,您可以使用以下命令来创建它:

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^'s+|'s+$/g,'');
  };
}

看看这个帖子。在快速搜索之后,似乎很多人都遇到了修剪的问题。