innerHTML: How To Avoid

前端 未结 5 450
孤城傲影
孤城傲影 2021-01-02 16:00

I\'m writing a plugin which will convert emoticons to images in a text block for a particular site. The easy answer is to use regular expressions to detect the trigger text

5条回答
  •  悲&欢浪女
    2021-01-02 16:51

    This is the same issue I have to obtain the full review on my Addon (ImageZone).

    I think is not a good idea for you to use innerHTML, since you will lost all event listeners registered on the targets node. I think you could use a code like this:

    var treeWalker = document.createTreeWalker(
     node,
     NodeFilter.SHOW_ALL,
     { acceptNode:function (node) {
             return node.nodeType == Node.TEXT_NODE ? 
                      NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
     }},false);
    
     or just
    
    var treeWalker = document.createTreeWalker(
     node,
     NodeFilter.SHOW_TEXT,
     { acceptNode:function (node) {return NodeFilter.FILTER_ACCEPT; }},false);
    
     while(treeWalker.nextNode()) {
         var n=walker.currentNode;
         var text=n.nodeValue;
         var a= text.split(/(--- your emoticon regexp code ---))/g);
         if (a.length > 1){
             n.insertAfter(document.createTextNode(a[0]));
             var img=document.createElement("img");
             switch (a[1]){
                 case '...': img.setAttribute('src','...'); break;
             } 
             // or img.setAttribute('src',emos_srcs[a[1]]);
    
             n.insertAfter(img);
             n.insertAfter(document.createTextNode(a[2]));
             n.parentNode.removeChild(n);
         }
    
     }
    

提交回复
热议问题