Javascript 脚本附加到头并从内联js调用时未定义函数
我已经创建了一个演示我的问题Javascript 脚本附加到头并从内联js调用时未定义函数,javascript,Javascript,我已经创建了一个演示我的问题 var textFromHTTPRequest = '<html>' + '<head>' + '<script>' + 'function myFunc() { alert("works"); }' + '</script>' + '</head>' + '<body>' + '<a href="#" onmou
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]);
}
但是如果你使用Chrome Inspector,你可以看到脚本确实被添加了
(请不要太担心为什么正在获取的页面使用onmouseover,我无能为力)我通过使用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);
浏览器不会“使用”非hitself创建的脚本
您有两种选择:
1-创建一个新脚本并使用另一个脚本的.innerHTML
var menuScript = document.createElement('script');
menuScript.innerHTML = el.firstChild.querySelector('head script').innerHTML;
jsBin:
2-使用评估
您可以在该脚本上运行eval
,否则浏览器将无法对其进行全局化:
// Insert the script into current head tag.
eval(menuScript.textContent);
jsBin:默认情况下,html页面将有
html
,头
,&体
标记。那么是否需要再次创建?问题是关于未定义的函数。不要在示例场景中戳洞,这是问题的一个最低限度的演示:)这样做之后,您在元素源代码中看到了多少头,体&html
标记?每个标记只有一个
// Insert the script into current head tag.
eval(menuScript.textContent);