jquery查找和替换文本,没有元素ID [英] jquery find and replace text, without element id
问题描述
我正在寻找和替换文本.
I'm playing around with finding and replacing text.
我遇到的唯一问题是查找未附加到具有 ID 的元素的文本字符串.否则就容易了.
The only problem I'm having is finding a text string, that is not attached to an element with an ID. Otherwise, it would be easy.
我正在尝试这样的事情:
I'm trying something like this:
$("*").each(function () {
$(this).html(this.html().replace('Original Text','New Text'));
});
效果不太好.
以前有人遇到过这种情况吗?
Not working too well.
Anyone run into this before?
此外,如果我要查找和替换多个单词或短语,这对用户浏览器的速度/处理能力有何影响?是内存占用吗?
Also, if I have several words or phrases to find and replace, how does that affect the speed/processing power of the user's browser? Is it a memory hog?
推荐答案
Takpar,你的代码也能用.它似乎阻止了其他一些事情的工作,但只有我动态拉动的项目.例如,当我使用 .ajax()
时.不知道为什么,但这就是我遇到的原因.我会测试更多.
Takpar, your code works too. It seems to stop a few other things from working, but only items I'm pulling dynamically. For example, when I'm using .ajax()
. Not sure why, but that's why I ran into. I'll test more.
在相关主题上,Gumbo 的代码有效:
On a related topic, Gumbo's code works:
$("*").each(function () {
if ($(this).children().length == 0) {
$(this).text($(this).text().replace('Subject:','Name:'));
}
});
我遇到的唯一问题是替换页面加载后加载的文本.
The only thing I'm running into issues with is replacing text that is loaded after the page loads.
我确实有一些 javascript 函数可以显示来自服务器的数据,但只有在页面加载了所有元素之后.例如,用户从下拉列表中选择一个值,该值启动一个事件以从数据库加载产品列表.
I do have some javascript functions that are displaying data from the server, but only after the page has loaded all elements. For example, a user selects a value from a dropdown that initiates an event to load a list of products from the database.
我将其中一些产品格式化如下:
I format some of those products like this:
Granny Smith Apples
Price: x.xx per pound
Nutritional facts....
我只想找到一个替代词价格:",并可能将其替换为成本:".
I will only want to find a replace the word "Price:", and possibly replace it with "Cost:".
但正如我所提到的,该数据尚未加载.
But as I mentioned, that data has not been loaded yet.
我必须忍受一个限制吗?
Is a limit I have to live with?
这篇关于jquery查找和替换文本,没有元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!