[英]Replace a text in html tag without effecting tags attributes and links
我想替換代碼中的特定單詞而不影響html URL和屬性。 我試圖替換每個p標簽,但div標簽中有一些內容也需要更換。
$("p:not(:has(img))").each(function(){
var b = $(this).html().replace(/oldtext/g, "newtext");
$(this).html(b);
});
我為你寫了一個vanilla JavaScript函數,除了oldtext
到newtext
沒有任何改變:
replaceAllTextWith = function (jq, oldtxt, newtxt) {
for (var j = 0; j < jq.length; j++) {
var el = jq[j];
for (var i = 0; i < el.childNodes.length; i++) {
var cnode = el.childNodes[i];
if (cnode.nodeType == 3) {
console.log(el.tagName);
var nval = cnode.nodeValue;
//add .toLowerCase() here if you want to consider capital letters
if (-1 < nval.indexOf(oldtxt)) {
cnode.nodeValue = nval.replace(new RegExp(oldtxt, "g"), newtxt);
}
} else if (cnode.nodeType == 1) {
replaceAllTextWith([cnode], oldtxt, newtxt);
}
}
}
};
你可以稱之為:
replaceAllTextWith($("p:not(:has(img))"), "oldtext", "newtext")
這是一個有趣的任務,因為jquery的html()
只顯示選擇器內的html,但不顯示嵌套元素的html
解決方案是逐行分解html代碼(塊)並檢查是否存在某個元素(img),以便執行替換。
這是html:
<div id="a_unique_wrap_id">
<p><img src="https://www.google.pt/images/srpr/logo11w.png" /><h1>abc</h1></p>
<p><img src="https://www.google.pt/images/srpr/logo11w.png" />def</p>
<p><h1><span><b>abc</b></span></h1></p>
<div><h1><span><b>abc</b></span></h1></div>
<div><h1><span><b>def</b></span></h1></div>
</div>
這是javascript:
selector=$('div');
exclude='<img';
str=(selector.html().split('\n'));
l=str.length;
output='';
for(x=0;x<l;x++){
if(str[x].indexOf(exclude)>=0){
output+=str[x];
}else output+=str[x].replace(/abc/g, "newtext");
}
$('#a_unique_wrap_id').html(output);
一個工作的例子在這里: http : //jsfiddle.net/hbrunar/w6BfL/6/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.