Javascript在页面上查找文本 [英] Javascript find text on page

查看:75
本文介绍了Javascript在页面上查找文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to run a search and replace on HTML similar to the following... I need to have "Find Next" "Replace" and "Replace All" options.... the trick is that I need to run an AJAX request to update the values in the database for each field once the value is replaced.

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

The only trouble I'm running into is that I"m unsure exactly how to search the contents of #sheet and replace the values with the new value the user has provided.

<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个.

I should say that it's possible I'll have TONS of text to search, so ideally I'd only find the next instance of the item that's being searched for, not all instances. So when I hit "Find Next", if I"m 3 items in, it'll go to the 4th.

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

What's the best way in javascript to maintain the indexing on this without storing all found results in a variable and causing lag on the page?

推荐答案

我将在遍历匹配的元素时构建一个数据对象.然后发送对象,这样您就不会有来自循环的多个ajax请求. jsfiddle :

I would build a data object while traversing matched elements. Then send the object so you do not have multiple ajax request from a loop. 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`

这篇关于Javascript在页面上查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆