I have a loop on $(document).ready to check though a an array of text which calls a function to search for each snippet of text within an element and use that as a selector.

This code works 100% in FF, Chrome, IE9+ etc.. but freezes up the browser in 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); 
    });
});

I've disabled the setText function and it works fine, so its not the loop, it seems to be the :contains selector.

Why is this happening? How else can I do this? I cant edit the HTML code itself.

The idea is I have to change parts of the HTML markup with jQuery, add some HTML and change some CSS values, but the only unique Identifier I have is the text within '.item_name'.

The page in question which freezes that this is run on contains at most 3 separate instances of '.item_name'. Any of which may be targeted depending on the searches string.

I am using jQuery 1.7.1, can not update this.

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

没有正确的解决方案

其他提示

This looks to be a selector performance problem.

I would suggest the following steps
1. Add a id like id="crazy-products" the the container which contains all the item_name elements
2. Change $('.item_name:contains("'+value+'")') to $('.item_name:contains("'+value+'")', $('#crazy-products'))

IE8 or below does not have the document.getElementsByClassName implementation so it is looking all the elements in the document to see whether the given filter condition is applied to it. If we can pass an context to the filter condition we can narrow the scope of the document lookup thus improving the performance of the page.

For better understanding of the problem you can look at jquery.js line number 4215 (found = filter( item, match, i, curLoop )) and look at the size of the array curLoop, it looks to be enormously large in your case, by passing a id based context to the filter can can reduce it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top