简体   繁体   中英

How to use js/jquery to search text appended previously

I have a page that pulls information from an off-site resource, and appends information to the page. This is a large amount of data and it takes several minutes to collect and append it all.

I'm using ajax to pull in the data, and jQuery's .append() to post to my page. I then have another function that I can fire that takes in a search term and looks through out the body for matching words and counts the total matches.

I realize there is something fundamentally wrong with the approach I have taken to search for data outside the DOM, but I am open to alternatives.

My search function looks like this:

function qtySearch(){
    var term = $('.qtySearch').val();
    var termRegex = new RegExp ("\\b" + term + "\\b", "gi");
    var matchRez = $(document.body).text ().match (termRegex);
    var termCount   = matchRez ? matchRez.length : 0;

    var countReport = "";
    switch (termCount) {
            case 0:
                countReport = '"'+term+'" was not found!'
            break;
            case 1:
                countReport = '"'+term+'" was found one time.'
            break;
            default:
                countReport = '"'+term+'" was found ' + termCount + ' times.'
            break;
     }

    $("#searchResults").text(countReport);
}

To elaborate, the above code does work to search all elements already displayed on pageload. However, it fails to match any terms that are drawn through an .append() after pageload.

Karl-André Gagnon, Thanks! Sometimes I can't see the forest for the trees. I had run into problems accessing info after appends in the past and thought this was more of the same.

Actually, the way I had formatted the text prohibited me from using no word breaks on either side of my regex to identify whole words only. If the word was first or last it wasn't returning it at all. Ultimately I'm not sure if the append prevented it from picking up the carrots or if it was just the fact that I was searching the page text, but after adjusting the regex it is now working.

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