在html替换文本如何设置,在JavaScript中,如何替换HTML页面中的文本而不影响标签?...

不要使用正则表达式来解析HTML。 [X] [HT] ML不是常规语言,不能可靠地使用正则表达式处理。您的浏览器内置了一个很好的HTML解析器;让它能够解决标签在哪里的问题。

此外,你也不想在身体上工作html()/innerHTML。这将对整个页面进行序列化和重新解析,这将会很慢,并且会丢失HTML中无法序列化的任何信息,例如事件处理程序,表单值和其他JavaScript引用。

下面是使用DOM的方法,似乎为我工作:

function replaceInElement(element, find, replace) {

// iterate over child nodes in reverse, as replacement may increase

// length of child node list.

for (var i= element.childNodes.length; i-->0;) {

var child= element.childNodes[i];

if (child.nodeType==1) { // ELEMENT_NODE

var tag= child.nodeName.toLowerCase();

if (tag!='style' && tag!='script') // special case, don't touch CDATA elements

replaceInElement(child, find, replace);

} else if (child.nodeType==3) { // TEXT_NODE

replaceInText(child, find, replace);

}

}

}

function replaceInText(text, find, replace) {

var match;

var matches= [];

while (match= find.exec(text.data))

matches.push(match);

for (var i= matches.length; i-->0;) {

match= matches[i];

text.splitText(match.index);

text.nextSibling.splitText(match[0].length);

text.parentNode.replaceChild(replace(match), text.nextSibling);

}

}

// keywords to match. This *must* be a 'g'lobal regexp or it'll fail bad

var find= /\b(keyword|whatever)\b/gi;

// replace matched strings with wiki links

replaceInElement(document.body, find, function(match) {

var link= document.createElement('a');

link.href= 'http://en.wikipedia.org/wiki/'+match[0];

link.appendChild(document.createTextNode(match[0]));

return link;

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值