添加< script>元素到DOM并有JavaScript运行? [英] Adding <script> element to the DOM and have the javascript run?

查看:80
本文介绍了添加< script>元素到DOM并有JavaScript运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我对YUI做了这个:

  var scriptNode = Y.Node.create('< script type =text / javascriptcharset =utf-8> alert(Hello world! );< \ /脚本>'); 
var headNode = Y.one('head');
headNode.append(scriptNode);

它已成功添加到DOM,但它不会给我提示。



有人知道问题是什么?

解决方案

我不知道YUI的 Node.create()函数可以工作,所以对此没有评论。但是一个简单的跨浏览器脚本是:

pre $ window $ on $ = function(){
var s = document。的createElement( '脚本');
s.type ='text / javascript';
var code ='alert(hello world!);';
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch(e){
s.text = code;
document.body.appendChild(s);


try..catch 块是必要的,因为大多数浏览器都喜欢第一种方法,但有些则不会抛出错误。第二种方法涵盖那些。您也可以简单地 eval 代码,它或多或少是等价的,以及一些库的功能。


I want to add a element into the existing DOM to have the javascript code run.

I did this with YUI:

var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>');
var headNode = Y.one('head');
headNode.append(scriptNode);

It's successfully added to the DOM but it doesn't give me an alert.

Someone knows what the problem is?

解决方案

I have no idea how YUI's Node.create() function works, so no comment on that. But a simple cross-browser script is:

  window.onload = function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    var code = 'alert("hello world!");';
    try {
      s.appendChild(document.createTextNode(code));
      document.body.appendChild(s);
    } catch (e) {
      s.text = code;
      document.body.appendChild(s);
    }
  }

The try..catch block is necessary as most browsers like the first method but some don't and throw an error. The second method covers those. You can also simply eval the code, which is more or less equivalent and what some libraries do.

这篇关于添加&lt; script&gt;元素到DOM并有JavaScript运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆