Can't append [removed] element

后端 未结 18 2188
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 06:11

Any idea why the piece of code below does not add the script element to the DOM?

var code = \"\";
$(\"#someElement\").append(cod         


        
相关标签:
18条回答
  • 2020-11-21 06:45
    <script>
        ...
        ...jQuery("<script></script>")...
        ...
    </script>
    

    The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.

    0 讨论(0)
  • 2020-11-21 06:46

    What do you mean "not working"?

    jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -

    $('#someElement').append('<script>alert("WORKING");</script>');
    

    Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.

    0 讨论(0)
  • 2020-11-21 06:46

    This is what I think is the best solution. Google Analytics is injected this way.

    var (function(){
        var p="https:" == document.location.protocol ? "https://" : "http://";
            d=document,
            g=d.createElement('script'),
            s=d.getElementsByTagName('script')[0];
            g.type='text/javascript';
            g.src=p+'url-to-your-script.js';
            s.parentNode.insertBefore(g,s); })();
    
    0 讨论(0)
  • 2020-11-21 06:48

    It is possible to dynamically load a JavaScript file using the jQuery function getScript

    $.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
      Display.sharePrice();
    });
    

    Now the external script will be called, and if it cannot be loaded it will gracefully degrade.

    0 讨论(0)
  • 2020-11-21 06:50

    I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:

    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src = url;
    $("#someElement").append( script );
    

    From: JSON for jQuery

    0 讨论(0)
  • 2020-11-21 06:51

    Try this may be helpful:

    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src","scriptAnalytics.js");
    document.getElementsByTagName("head")[0].appendChild(fileref);
    
    0 讨论(0)
提交回复
热议问题