2016-07-15 40 views
0

HTML:outerHTML数据不完整

<div id="WholeNew"> 
    <script>func2()</script> 
    <img src="x" onerror=func1() /> 
</div> 

JS:

function func1() 
{ 
    console.log(arguments.callee.caller.arguments[0].target.parentNode.outerHTML); 
} 

function func2() 
{ 
    console.log(document.currentScript.parentNode.outerHTML); 
} 

现在看控制台输出:

对于FUNC1():

<div id="WholeNew"> 
    <script>func2()</script> 
    <img src="x" onerror=func1() /> 
</div> 

对于FUNC2():

<div id="WholeNew"> 
    <script>func2()</script> 
</div> 

为什么有一个在两个输出的差值,如在func1()func2()document.currentScript.parentNode相同<div>document.callee.caller.arguments[0].target元件?我需要从func2()完整的<div> outerHTML。

+0

哪些浏览器您使用?由于错误,我无法在IE11或Chrome51中复制该问题。可能与该被调用者有关系已被弃用。不要迂腐,但你想用这段代码解决什么问题,因为这看起来不像是最好的设计。 – Shilly

+0

我可以在Chrome 51和Firefox 47中成功运行代码。由于使用了“target”,IE无法工作。使用'srcElement'。你会得到什么错误?我只是试验这个特定的代码行为。 –

+0

根据我放置函数定义的位置,我得到的调用者或被调用者都是未定义的。您在哪个位置触摸了包含这些功能的脚本?你有没有尝试过这与一个实际的图像网址?也许src是'x'正在搞东西。 – Shilly

回答

1

问题是,当询问document.currentScript.parentNode该文件尚未准备好。尝试检索outerHTMLDOMContentLoaded

function func2() 
{ 
    currentScriptReference = document.currentScript; 
    document.addEventListener('DOMContentLoaded', function(){ 
     console.log(currentScriptReference.parentNode.outerHTML); 
    }, false); 
} 

工作plunker:https://plnkr.co/edit/koZ1xDlpFacm7r9uY8lC?p=preview

控制台日志的结果:

<div id="WholeNew"> 
    <script>func2()</script> 
    <img src="x"> 
</div> 
+0

谢谢。 +1。这清除了它。 –