你將不得不尋找在文檔中的文本節點,我使用遞歸函數如下:
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