$('。item name:contains(“text”)')导致IE8在页面加载时冻结

时间:2013-01-25 00:34:55

标签: jquery internet-explorer loops jquery-selectors internet-explorer-8

我在$(document).ready上有一个循环来检查一个文本数组,它调用一个函数来搜索元素中的每个文本片段并将其用作选择器。

此代码在FF,Chrome,IE9 +等中100%有效。但在IE8中冻结浏览器。

var setText = function(value)
{
    if(typeof $('.item_name:contains("'+value+'")') != 'undefined'){
      // Do something, it still freezes with nothing set here.
    }
}

// In the real script there maybe upwards of 20 items in this array.
var item_list = new Array('a','b','c');

$(document).ready(function() 
{
    $.each(item_list, function(index, value) {
       setText(value); 
    });
});

我已经禁用了setText函数并且它工作正常,所以它不是循环,它似乎是:contains选择器。

为什么会这样?我怎么能这样做?我无法编辑HTML代码本身。

我的想法是我必须使用jQuery更改部分HTML标记,添加一些HTML并更改一些CSS值,但我唯一唯一的标识符是'.item_name'中的文本。

冻结运行此问题的页面最多包含3个'.item_name'的单独实例。根据搜索字符串,可以定位任何一个。

我使用的是jQuery 1.7.1,无法更新此内容。

if($('.item_name:contains("'+value+'")').length > 0){ // Also causes it to freeze.

1 个答案:

答案 0 :(得分:0)

这看起来是选择器性能问题。

我建议采取以下步骤 1.在包含所有id="crazy-products"元素的容器中添加item_name之类的ID 2.将$('.item_name:contains("'+value+'")')更改为$('。item_name:contains(“'+ value +'”)',$('#crazy-products'))

IE8或更低版本没有document.getElementsByClassName实现,因此它查找文档中的所有元素以查看是否对其应用了给定的过滤条件。如果我们可以将上下文传递给过滤条件,我们可以缩小文档查找的范围,从而提高页面的性能。

为了更好地理解这个问题,您可以查看jquery.js行号4215(found = filter( item, match, i, curLoop ))并查看数组curLoop的大小,在您的情况下,它看起来非常大,通过将基于id的上下文传递给过滤器可以减少它。