Dynamically adding script element to a div does not execute the script

后端 未结 2 688
谎友^
谎友^ 2020-12-21 03:38

I am trying to add a script block dynamically to the document. When I do this, the script block is not getting executed.


    
2条回答
  •  臣服心动
    2020-12-21 04:17

    In your first try you are creating a string and js interpreter handle it as a string, not an html tag, so js doesn't really care about your script tags presented in that string.

    Then of course it's working when you start using eval() because eval - is evil:))

    After all you can create script tags dynamically and then fill it with code:

    var elem = document.getElementById("dynamicDiv"),
        scriptTag = document.createElement('script'),
        scriptTagCode = 'function hello (val){alert("hello " + val);}';
    
    scriptTag.innerHTML = scriptTagCode;
    elem.appendChild(scriptTag);
    hello('foo');
    

提交回复
热议问题