How to Append [removed][removed] in javascript? [d

2019-01-02 15:45发布

This question already has an answer here:

I need to use childappend or jquery append() to append some tag stuff into the document. From what I can tell, this is getting stripped out. Anyone know how to do it?

6条回答
只若初见
2楼-- · 2019-01-02 16:01
$('<script>alert("hi");</' + 'script>').appendTo(document.body);

DEMO

查看更多
高级女魔头
3楼-- · 2019-01-02 16:04
// Create the element

var script = document.createElement("script");

// Add script content

script.innerHTML = "...";

// Append

document.head.appendChild(script);

Or

document.body.appendChild(script);
查看更多
无色无味的生活
4楼-- · 2019-01-02 16:05

This worked for me..

<script>
    $('head').append("<script>your script content here<\/script>");
</script>

Note that the "/" of the inner </script> has been escaped to be "<\/script>". If it is not, it actually closes the outer <script> tag.

The script added wont be visible but will get executed. Hope that helps.

查看更多
几人难应
5楼-- · 2019-01-02 16:11

Try this:

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);

Note that the script will load and you can access the variables inside it, but you wouldn't see the actual <script> tag in the DOM.

查看更多
泛滥B
6楼-- · 2019-01-02 16:14

If you need to append a script so that it's parsed you could do as google does for his +1 button

  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'link to your script here';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
查看更多
美炸的是我
7楼-- · 2019-01-02 16:17
$('your_document_selector').text('<script></script>')

.text() makes it possible to append script tags with it being rendered as HTML.

OR

$('your_document_selector').append('&lt;script&gt;&lt;/script&gt;')
查看更多
登录 后发表回答