Can't append [removed] element

2018-12-31 00:54发布

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

var code = "<script></script>";
$("#someElement").append(code);

18条回答
看风景的人
2楼-- · 2018-12-31 01:14

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);
查看更多
栀子花@的思念
3楼-- · 2018-12-31 01:16

Adding the sourceURL in the script file helped as mentioned in this page: https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/

  1. In the script file, add a statement with sourceURL like "//@ sourceURL=foo.js"
  2. Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools
查看更多
零度萤火
4楼-- · 2018-12-31 01:16

Can try like this

var code = "<script></" + "script>";
$("#someElement").append(code);

The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.

查看更多
永恒的永恒
5楼-- · 2018-12-31 01:21

You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:

const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
  (function(i,s,o,g,r,a,m){a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.innerText=g;a.onload=r;m.parentNode.insertBefore(a,m)})(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))

It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.

查看更多
初与友歌
6楼-- · 2018-12-31 01:22

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

查看更多
像晚风撩人
7楼-- · 2018-12-31 01:23

Just create an element by parsing it with jQuery.

<div id="someElement"></div>
<script>
    var code = "<script>alert(123);<\/script>";
    $("#someElement").append($(code));
</script>

Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

查看更多
登录 后发表回答