原型函数在IE8中不起作用

Prototype function not working in IE8

本文关键字:不起作用 IE8 函数 原型      更新时间:2023-09-26

我最近问了一个问题,得到了一个有效的工作答案。然而,当时我正在 Firefox 中进行测试,虽然一切看起来都很好,但所需的浏览器 IE8 不喜欢这个功能。

我正试图找到它的替代品。

这是我的原始问题:jQuery 按条件过滤行

这是有效的答案(虽然不是在IE8中):

// collating the 'regions':
var regions = ['americas', 'emea', 'apac'],
// initialising an array to use, later:
    foundClasses = [];
// iterating over the 'tr' elements, filtering them:
$('tr').filter(function () {
    // using Array.prototype.forEach to filter the classList of the element:
    foundClasses = Array.prototype.filter.call(this.classList, function (c) {
        // 'c' is the current class in the classList we're iterating over,
        // if it's in the array we return that array to the 'foundClasses':
        if (regions.indexOf(c) > -1) {
            return c;
        }
    });
    // we keep the the element in the jQuery collection (of 'tr' elements),
    // if we do not have exactly 2 of the allowed classes...
    return foundClasses.length !== 2;
// removing those 'tr' elements:
}).remove();

我对原型知之甚少,所以我只是使用它,因为它满足了我需要的作用,但欢迎任何其他解决方案。

如评论中所述。 IE8 中不存在Array.prototype.filter。相反,您可以使用jQuery的grep()

// collating the 'regions':
var regions = ['americas', 'emea', 'apac'];
// iterating over the 'tr' elements, filtering them:
$('tr').filter(function () {
    var foundClasses = $.grep(this.className.split(/'s+/), function (c) {
        return $.grep(regions, function(r) { return r === c; }).length > 0;
    });
    // we keep the the element in the jQuery collection (of 'tr' elements),
    // if we do not have exactly 2 of the allowed classes...
    return foundClasses.length !== 2;
}).remove();

请注意,在 IE 10 之前,IE 也不支持.classList。相反,您可以使用 this.className.split(/'s+/) ,如上所述。