[英]Replace content of each HTML controls javascript jquery
I'm trying again to replace each text content of each control in a page using javascript and jquery. 我再次尝试使用javascript和jquery替换页面中每个控件的每个文本内容。
I need to search in each text content (WITHOUT MODIFING TAGS, ONLY THE TEXT) any word and replace it with another any word. 我需要在每个文本内容中搜索任何词(不带标记,仅修改文本),然后用另一个词替换它。
One try is: 一种尝试是:
jQuery.fn.replaceEachOne = function (objective, rep) {
this.each( function(){
//$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
$(this).html( $(this).html().replace( new RegExp('('+objective+'(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
}
);
}
Please help!! 请帮忙!!
Something like this should do the trick: 这样的事情应该可以解决问题:
$.fn.replaceEachOne = function(search, replace) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(search, replace);
} else if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = this.nodeValue.replace(search, replace);
}
});
};
This does the replacement on text nodes directly, rather than modifying the HTML of an entire element. 这将直接在文本节点上进行替换,而不是修改整个元素的HTML。 Note that it is case-sensitive. 请注意,它区分大小写。 You'd need to change the call to replace
to use a regular expression if you want a case-insensitive search. 如果想要不区分大小写的搜索,则需要将调用replace
为使用正则表达式。
I would start by something like this: 我将从这样的事情开始:
jQuery.fn.replaceEachOne = function(objective, rep) {
var html = jQuery(this).html();
var simpleRegexp = new RegExp(objective, "gi");
var regexp = new RegExp(">[^><]*?"+objective+"[^><]*?<","gi");
html = html.replace(regexp, function(match) {
return match.replace(simpleRegexp, rep);
});
jQuery(this).html(html);
}
That code finds the matching text in body html code beetween '>'
and '<'
characters and then replaces matched text. 该代码在'>'
和'<'
字符之间的正文html代码中找到匹配的文本,然后替换匹配的文本。
Of course this is simple solution and it will replace text also in <script>
or <style>
blocks. 当然,这是简单的解决方案,它还将替换<script>
或<style>
块中的文本。 By I think it is a good idea to start with. 我认为这是一个好主意。
Finally... 最后...
jQuery.fn.replaceEachOne = function (objective, reposition) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(objective, reposition);
} else if (this.nodeType == Node.TEXT_NODE) {
var label = document.createElement("label");
label.innerHTML = this.nodeValue.replace(objective, reposition);
this.parentNode.insertBefore(label, this);
this.parentNode.removeChild(this);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.