简体   繁体   English

无法在JavaScript中附加document.body.appendChild

[英]Unable to append javascript with document.body.appendChild

I'm trying to append javascript to a loaded page by: 我试图通过以下方式将javascript附加到加载的页面:

var sc = document.createElement('script');
sc.content = "<script>alert('aa')</script>";
document.body.appendChild (sc);

But that didn't work in chromium: 但这不适用于铬:

在此处输入图片说明

You don't put <script>...</script> inside the content of a script element. 您不要将<script>...</script>放在script元素的内容内。 But more to the point, I don't think they have a content property (I don't see one here , for instance). 但更重要的是,我认为它们没有content属性(例如,我在这里没有看到 )。

If I recall correctly, the most reliable way to put content within a script element at runtime is via createTextNode and appendChild , eg: Live example | 如果我没记错的话,在运行时将内容放入script元素中的最可靠方法是通过createTextNodeappendChild ,例如: 实时示例 | source 资源

var sc = document.createElement('script');
sc.appendChild(document.createTextNode("alert('aa')"));
document.body.appendChild(sc);

...but I wouldn't be surprised to find that some older browsers required you to set innerText or something instead. ...但是如果发现某些较旧的浏览器要求您设置innerText或其他内容,我不会感到惊讶。

var script = document.createElement('script');
script.appendChild(document.createTextNode("alert('http://jsfiddle.net/UpWhX/')"));
document.body.appendChild(script);

Try this TestHere http://jsfiddle.net/UpWhX/2/ 试试这个TestHere http://jsfiddle.net/UpWhX/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM