简体   繁体   English

如何使用js / jquery搜索先前附加的文本

[英]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. 我使用ajax提取数据,并使用jQuery的.append()发布到我的页面。 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. 我意识到我在DOM之外搜索数据的方法存在根本上的错误,但是我愿意接受其他选择。

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. 但是,它无法匹配页面加载后通过.append()绘制的任何术语。

Karl-André Gagnon, Thanks! Karl-AndréGagnon,谢谢! 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. 如果单词是first或last,则根本不会返回它。 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. 最终,我不确定附件是否阻止它拾起胡萝卜,或者仅仅是我搜索页面文本的事实,但是在调整了正则表达式后,它现在可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM