如何使用jQuery查找文本并替换 [英] How to Find text and replace using jQuery
问题描述
我正试图找到一种解决方案,以搜索DOM中包含的文本字符串"Tony",并将其替换为文本字符串"Tiger".
Im trying to find a solution to search for a text string "Tony" contained in the DOM and replace it with a text String "Tiger".
任何人对此有任何见解或想法吗?我想这将需要每个语句加上一个替换函数,并且可能包含吗?
Anyone have any insight or ideas of how to do so? Im guessing it will take an each statement coupled with a replace function and possibly contains?
谢谢 杰克
推荐答案
您可以使用它搜索body元素的所有子元素并替换文本...
You can use this to search all children of the body element and replace the text...
$('body').children().each(function(){$(this).text( $(this).text().replace('Tony','Tiger') )});
它使用jQuery.它也应该只更改元素的文本内容,而不能更改任何HTML格式...
It uses jQuery. It also should only alter the textual content of elements and none of the HTML formatting...
您还可以使用此方法,该方法使用RegExp并获取所有嵌套元素:
You can also use this method which uses a RegExp and will get all nested elements:
$('body').html( $('body').html().replace(/Tony/gi,'tiger') );
这篇关于如何使用jQuery查找文本并替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!