动态创建的脚本未执行 [英] Dynamically created script not executing

查看:58
本文介绍了动态创建的脚本未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将脚本标记以及一堆其他html附加到从ajax调用中检索到的当前文档中.由于某种原因,脚本未运行

I am appending a script tag, along with a bunch of other html, to my current document, retrieved from an ajax call. For some reason the script is not running

//Response handling function
function(responseText){
    document.getElementById('reportContainer').insertAdjacentHTML('afterbegin',responseText);
}

responseText 内容的示例:

<h2>You are <em class="won">victorious</em>!</h2>
<h3>Earnings</h3>
... 
<script>
    alert('dgd');
</script>

所有的html都将应用于文档,包括脚本,但未运行,我没有弹出此警报.可能是什么原因造成的?

All the html is getting applied to the document, including the script, but it is not running, I don't get this alert popping. What may be causing this?

推荐答案

检查以下代码段,并将函数调用为

Check the following snippet and call the function as

var newEle = document.querySelector("#reportContainer");
exec_body_scripts(newEle);

功能

exec_body_scripts = function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.

  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};

这篇关于动态创建的脚本未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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