开发者社区> 问答> 正文

脚本附加到头部并从内联js调用时未定义函数

我创建了这个jsbin并演示了我的问题。

var textFromHTTPRequest = '<html>'
    + '<head>'
      + '<script>'
        + 'function myFunc() { alert("works"); }'
      + '</script>'
    + '</head>'
    + '<body>'
      + '<a href="#" onmouseover="myFunc()">test</a>'
    + '</body>'
  + '</html>';

// Parse the text to dom element.
var parser = new DOMParser();
var el = parser.parseFromString(textFromHTTPRequest, "text/html");

// Get the script and contents of body.
var menuBody = el.firstChild.querySelectorAll('body > *');
var menuScript = el.firstChild.querySelector('head script');

// Insert the script into current head tag.
document.head.appendChild(menuScript);

// Insert the contents of body into current body.
for (var i = 0; i < menuBody.length; ++i) {
  document.body.appendChild(menuBody[i]);
}

它正在复制的方案是使用Fetch提取HTML文档。

该代码解析文本,然后提取正文内容。体内的某些东西会使用内联鼠标悬停。因此,我还需要拉入script标签。

但是,鼠标悬停现在不起作用。

展开
收起
游客ufivfoddcd53c 2020-01-04 14:14:40 865 0
1 条回答
写回答
取消 提交回答
  • 我自己修复了该问题,方法是使用createElement并将脚本内容复制到其中。这样可行。会的

    var menuScript = el.firstChild.querySelector('head script');
    
    var script = document.createElement( 'script' );
    script.innerHTML = menuScript.innerHTML;
    
    // Insert the script into current head tag.
    document.head.appendChild(script);
    
    2020-01-04 14:15:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript异步编程 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载