簡體   English   中英

用Javascript替換dom中每個單詞的實例

[英]Replace every instance of a word in the dom with Javascript

我正在嘗試使用我正在制作的Chrome擴展程序進行解析,並將一個單詞的所有實例替換為另一個。 這就是我不適合我的東西

function jamify() {
  $("body").html().replace(/James/g,"Jamie");
}

.html()的快速且相當臟的替換有兩個缺點。

  • 它實際上將替換整個DOM結構,如果未將這些事件綁定“實時”綁定到層次結構中較高的元素,則將其刪除
  • 它會替代很多東西,超出您的預期。 從“ James”到“ Jamie”應該是安全的,但是當“ em”想要被命名為“ emmy”並且突然斜體文本被弄清楚時,它可能會變得很時髦。

更好的方法是僅替換實際文本節點中的字符串,因為jQuery並非(當前)問題的標簽,我認為使用javascript是合適的選擇。

 var walker = document.createTreeWalker( document.body, NodeFilter.SHOW_TEXT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); while (walker.nextNode()) { walker.currentNode.data = walker.currentNode.data.replace(/James/g, 'Jamie'); } 
 <!-- James --> <div data-name="James" class="James"> James </div> 

此示例僅會觸摸實際的文本元素,注釋和兩個屬性( data-nameclass )都不會被替換,因此使用javascript和/或css引用它們仍然是安全的。

我以這種方式顯示它,表明您必須調用一些函數以將html重置為新替換的字符串

注意:這將銷毀您在替換之前附加的任何DOM事件

您可以通過嵌套調用各成一體,如果你想縮短這個

 function jamify() { var str = $(".test").html(); console.log('jamify', str); str2 = str.replace(/James/g,"Jamie"); $(".test").html(str2); //to simplify it could be done this way too //$(".test").html($(".test").html().replace(/James/g,"Jamie")) } $(document).ready(function(){ //alert('ready'); $('.inner').click(function(){console.log('inner click')}) //Yea!, my click event is all good. jamify(); //Now all your inner click EVENT is broken so this is not good //solution if there are any events attached in your DOM }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test"> <p>James is here</p> <div class="inner">this div is James</div> </div> 

如果單詞在textContent中,則可以嘗試:

 var all = document.querySelectorAll('.test') //using .test as a wrapper section, try using body in production as selector (in the snippets it breaks) all.forEach(x => x.textContent = x.textContent.replace(/James/gi, "Jamie")) // keep in mind forEach for nodes has limited support, tested in chrome 
 <div class="test"> <p>James is here</p> <div >this div is James</div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM