jQuery jquery查找和替换文本,没有元素ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2349138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery find and replace text, without element id
提问by coffeemonitor
I'm playing around with finding and replacing text.
我正在寻找和替换文本。
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.
我遇到的唯一问题是找到一个没有附加到带有 ID 的元素的文本字符串。否则,会很容易。
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?
另外,如果我要查找和替换多个单词或短语,这对用户浏览器的速度/处理能力有何影响?是内存猪吗?
采纳答案by coffeemonitor
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.
Takpar,你的代码也有效。它似乎阻止了其他一些事情的工作,但只有我动态拉动的项目。例如,当我使用.ajax()
. 不知道为什么,但这就是我遇到的原因。我会测试更多。
On a related topic, Gumbo's code works:
在相关主题上,Gumbo 的代码有效:
$("*").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.
我遇到的唯一问题是替换页面加载后加载的文本。
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.
我确实有一些 javascript 函数显示来自服务器的数据,但只有在页面加载所有元素之后。例如,用户从下拉列表中选择一个值,该值启动一个事件以从数据库加载产品列表。
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?
我必须忍受一个限制吗?
回答by user187291
$("*").contents().each(function() {
if(this.nodeType == 3)
this.nodeValue = this.nodeValue.replace("old", "new");
});
回答by Alexar
why don't you simply use:
你为什么不简单地使用:
$('body').html($('body').html().replace('Original Text','New Text'));
回答by Alexar
You want the :contains()
selector. http://api.jquery.com/contains-selector/
你想要:contains()
选择器。http://api.jquery.com/contains-selector/
$("*:contains('Original Text')").each(...);
回答by Rony T Sam
$("*").each(function () {
if ($(this).children().length == 0){
$(this).html($(this).html().replace(/Old String/g, "New String"));
}});