Executing [removed] elements inserted with [removed]

后端 未结 20 2545
囚心锁ツ
囚心锁ツ 2020-11-22 00:12

I\'ve got a script that inserts some content into an element using innerHTML.

The content could for example be:



        
20条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 01:04

    Simplified ES6 version of @joshcomley's answer with an example.

    No JQuery, No library, No eval, No DOM change, Just pure Javascript.

    http://plnkr.co/edit/MMegiu?p=preview

    var setInnerHTML = function(elm, html) {
      elm.innerHTML = html;
      Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
        const newScript = document.createElement("script");
        Array.from(oldScript.attributes)
          .forEach( attr => newScript.setAttribute(attr.name, attr.value) );
        newScript.appendChild(document.createTextNode(oldScript.innerHTML));
        oldScript.parentNode.replaceChild(newScript, oldScript);
      });
    }
    

    Usage

    $0.innerHTML = HTML;    // does *NOT* run 
    
                                     
                  
提交回复
热议问题