简体   繁体   中英

Does IE8 have issues with JS switches?

I am building a piece of javascript that needs to be IE8 compatible. When testing my code, IE8 gets tripped up on my switch. I am unable any good documentation on why it would do this. So what I am looking for is a good resource or answer why this snippet of code is getting tripped up:

$div.attr('shippingtotal', price.trim());
            switch (method.trim().toUpperCase()) {
            case 'STANDARD GROUND':
                $div.attr('value', 'UG');
                break;
            case 'THIRD DAY GROUND':
                $div.attr('value', 'UTS');
                break;
            case 'SECOND DAY AIR':
                $div.attr('value', 'US');
                break;
            case 'NEXT DAY':
                $div.attr('value', 'UNN');
                break;
            }

The console error says it is coming from line 40 which falls on the third break.

The issue is not the switch but the use of String.prototype.trim . It's not implemented in IE8 and you need to polyfill it or use a lib that has a trim function eg jQuery.trim .

I think there is no problem with your switch . Try to use if-else instead of that, I am sure you will get the same error.

$div.attr('shippingtotal', price.trim());
var ucMethod = method.trim().toUpperCase();
if (ucMethod == 'STANDARD GROUND')
    $div.attr('value', 'UG');
else if (ucMethod == 'THIRD DAY GROUND')
    $div.attr('value', 'UTS');
else if (ucMethod == 'SECOND DAY AIR')
    $div.attr('value', 'US');
else if (ucMethod == 'NEXT DAY')
    $div.attr('value', 'UNN');

or

var valueMap = {
    'STANDARD GROUND': 'UG',
    'THIRD DAY GROUND': 'UTS',
    'SECOND DAY AIR': 'US',
    'NEXT DAY': 'UNN'
};

$div.attr('shippingtotal', price.trim());
$div.attr('value', valueMap[method.trim().toUpperCase()]);

You should not rely on ie8 error messages. You should write unit tests instead. I think it is possible to run them with karma . I guess the jquery has problems with ie8, but I am not sure...

I don't think ie8 support the trim() method. You should use a polyfill .

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

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