如何添加< script> DOM的元素并执行其代码? [英] How to add a <script> element to the DOM and execute its code?

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

问题描述

我想在现有的DOM中添加一个元素来运行javascript代码。

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

我用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);

它已成功添加到DOM但它没有给我提醒。

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

有人知道问题是什么吗?

Someone knows what the problem is?

推荐答案

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

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);
    }
  }

try..catch 块是必要的,因为大多数浏览器喜欢第一种方法,但有些浏览器不会抛出错误。第二种方法包括那些。您也可以简单地评估代码,这或多或少等同于某些库所做的。

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的元素并执行其代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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