你将不得不寻找在文档中的文本节点,我使用递归函数如下:
function replaceText(oldText, newText, node){
node = node || document.body; // base node
var childs = node.childNodes, i = 0;
while(node = childs[i]){
if (node.nodeType == 3){ // text node found, do the replacement
if (node.textContent) {
node.textContent = node.textContent.replace(oldText, newText);
} else { // support to IE
node.nodeValue = node.nodeValue.replace(oldText, newText);
}
} else { // not a text mode, look forward
replaceText(oldText, newText, node);
}
i++;
}
}
如果以这种方式做到这一点,您的标记和事件处理程序将保持不变。
编辑:更改代码来支持IE,因为IE浏览器的textnodes没有textContent属性,在IE浏览器,你应该使用nodeValue财产,它也不会实现了Node接口。
检查示例here。
来源
2009-10-03 05:25:43
CMS
非常感谢@CMS,您帮我解决了这个问题:http://stackoverflow.com/questions/1512053/how-to-force-breaking-of-non-breakable-strings/ – Sylvain 2009-10-03 07:02:10
'node.data'应该适用于所有浏览器。 – James 2009-10-03 14:38:50
一段很棒的代码,我们可以让它更快吗? – crosenblum 2010-01-27 21:05:40