Javascript 在页面上查找文本

Web*_*net 5 javascript jquery

我需要在 HTML 上运行搜索并替换,类似于以下内容...我需要有“查找下一个”、“替换”和“替换全部”选项...诀窍是我需要运行 AJAX 请求替换值后,更新数据库中每个字段的值。

我遇到的唯一麻烦是我不确定如何搜索内容#sheet并用用户提供的新值替换这些值。

<div id='sheet'>
<div class='item' id='field-18583'>This is yet another test</div>
<div class='item' id='field-18585'>This is test data</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我应该说,我可能有大量文本要搜索,所以理想情况下我只会找到正在搜索的项目的下一个实例,而不是所有实例。因此,当我点击“查找下一个”时,如果我有 3 个项目,它将转到第 4 个项目。

javascript 中维护索引的最佳方法是什么,而不将所有找到的结果存储在变量中并导致页面滞后?

Jos*_*ell 6

我将在遍历匹配元素时构建一个数据对象。然后发送该对象,这样就不会出现循环中的多个 ajax 请求。jsfiddle

<div class='item' id='field-18583'>This is yet another test</div>
<div class='item' id='field-18585'>This is test data</div>
Run Code Online (Sandbox Code Playgroud)

脚本:

var searchTerm = 'This is',
    replaceWith = 'This is new',
    updateObj = {};
$("#sheet div.item:contains('" + searchTerm + "')").each(function(){
   // use id to build an update object
    updateObj[this.id.replace('field-', '')] = {
        oldText: searchTerm, 
        newText: replaceWith
    }; // not sure what you are trying to save here
   // manipulate html
   this.innerHTML = this.innerHTML.replace(searchTerm, replaceWith);
});
// after, send ajax data `updateObj`
Run Code Online (Sandbox Code Playgroud)