Executing [removed] elements inserted with [removed]

后端 未结 20 2565
囚心锁ツ
囚心锁ツ 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:09

    Here's a shorter, more efficient script that also works for scripts with the src property:

    function insertAndExecute(id, text) {
        document.getElementById(id).innerHTML = text;
        var scripts = Array.prototype.slice.call(document.getElementById(id).getElementsByTagName("script"));
        for (var i = 0; i < scripts.length; i++) {
            if (scripts[i].src != "") {
                var tag = document.createElement("script");
                tag.src = scripts[i].src;
                document.getElementsByTagName("head")[0].appendChild(tag);
            }
            else {
                eval(scripts[i].innerHTML);
            }
        }
    }
    

    Note: whilst eval may cause a security vulnerability if not used properly, it is much faster than creating a script tag on the fly.

提交回复
热议问题