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

后端 未结 2 666
谎友^
谎友^ 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:12

    Would like to point out that the reason the 3rd snippet you provided works inside the for loop, but not outside is because you are using eval. eval takes a string and executes it as js, which is why it is working inside the loop, but using eval isn't parsing it for future use, which is causing it to be unusable elsewhere. Therefore, when you go to call it outside the loop, you get a reference error.

    UPDATE:

    If you are getting the string back with the <script> tags in it, you can just parse out the script tags.

    var string = "<script type=\"text\/javascript\"> ";
        string += "function hello (val)";
        string += "{";
        string += "alert('hello ' + val);";
        string += "}";
        string += "<\/script>";
    string = string.replace(/<(script|\/script).*?>/g,'');
    function createFunction() {
        var elem = document.getElementById("dynamicDiv");
        var script = document.createElement('script');
        script.innerHTML = string;
        elem.appendChild(script);
        hello("World 1");
    }
    createFunction()
    hello('world 2');
    

    JSFiddle: http://jsfiddle.net/3wYD6/

    I don't really see the point of this, but if you really want to do this you can create a new script element and then set it's innerHTML to the function, then append the new script to a div.

    var elem = document.getElementById("dynamicDiv"),
        script = document.createElement('script');
    script.innerHTML = 
        'function hello (val) {' +
            'alert("hello " + val);' + 
        '}';
    elem.appendChild(script);
    hello('world');
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
提交回复
热议问题