我再次尝试使用 javascript 和 jquery 替换页面中每个控件的每个文本内容。
我需要在每个文本内容(不修改标签,仅文本)中搜索任何单词并将其替换为另一个任何单词。
一次尝试是:
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) );
}
);
}
请帮忙!!
最佳答案
像这样的事情应该可以解决问题:
$.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);
}
});
};
这直接在文本节点上进行替换,而不是修改整个元素的 HTML。请注意,它区分大小写。如果您想要不区分大小写的搜索,则需要更改对 replace
的调用以使用正则表达式。
关于javascript - 替换每个 HTML 控件的内容 javascript jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4735946/