简体   繁体   中英

Jquery issues on older versions of IE

I have the following statement in document.ready function:

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

It works fine in IE 9 but as soon as I select IE 8 (browser and document standard), the script stops working and gives the following error:

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

I looked at the .js in debug mode and see that my statement above is transformed to:

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

How do I prevent this error? Please note that I do see that the node is present in the rendered page.

I thought that maybe just having reference to shiv5.html may not be sufficient to take care of the IE idiosyncrasies. So, I have added modernizr.js via sprockets and I have added class="no-js" in my layout. Still no luck in IE <9.

What am I missing? What else can I do to get the favor of Microsoft overlords?

According to MDN, trim isn't available in IE < 9.

You could use $.trim instead:

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

The MDN article lists an alternative if you don't want to find all the instances of trim and correct them. You could use the following to create .trim if it's not natively available:

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

Check out this thread. After a quick search it seems that many people are experiencing issues with trim.

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