jquery - 在页面上查找文本的 Javascript
我需要在类似以下内容的 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>
我应该说,有可能我会有大量的文本需要搜索,所以理想情况下,我只想找到正在搜索的项目的下一个实例,而不是所有实例。所以当我点击“查找下一个”时,如果我已经在第3个项目,它将跳到第4个。
在 JavaScript 中,维护这个索引的最佳方法是什么,而不将所有找到的结果存储在变量中并导致页面延迟?
答案#1
我会在遍历匹配的元素时构建一个数据对象。然后发送该对象,这样你就不会在循环中发出多个 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>
脚本:
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`
答案#2
如果你必须搜索/替换 HTML,那么使用 innerHTML 属性:
document.getElementById("sheet").innerHTML
但请注意,浏览器将 DOM 保存在内存中作为树,而不是作为 HTML。它只读取 HTML 来构建 DOM。因此你可能会发现按元素的更改更快。
