2017-01-12 53 views
-1

继在特定网站上的beginers教程和演示者代码工作,但我的不。 (我相信我们有完全相同的代码)。他的代码执行到警报框中提到的“正要调用第一个函数”的位置。但是,我的代码没有达到这一点。我错过了什么吗?跟踪和调试JS代码

我的HTML页面

<html> 
    <head> 
     <title>Debugging and Tracing through code</title> 
     <script src="tracing.js"></script> 
    </head> 

    <body> 
     <p>Example of tracing through code.</p> 
     <h1 id="mainHeading">Interesting Headline</h1> 
    </body> 
</html> 

我的js代码

function firstFunction() { 
    secondFunction(); 
} 

function secondFunction() { 
    thirdFunction(); 
} 

function thirdFunction() { 
    fourthFunction(); 
} 

function fourthFunction() { 
    headline.innerHTML = "You clicked the headline!"; 
} 

var headline = document.getElementById("mainHeading"); 
alert("Ive grabbed main heading"); 
headline.onclick = function() { 
    alert("just about to call first function"); 
    firstFunction(); 
    alert("I've called first function"); 
}; 

错误

2 Missing 'use strict' statement. secondFunction(); 
2 Expected 'secondFunction' at column 5, not column 4. secondFunction(); 
2 'secondFunction' was used before it was defined. secondFunction(); 
6 Missing 'use strict' statement. thirdFunction(); 
6 'thirdFunction' was used before it was defined. thirdFunction(); 
10 Missing 'use strict' statement. fourthFunction(); 
10 'fourthFunction' was used before it was defined. fourthFunction(); 
14 Missing 'use strict' statement. headline.innerHTML = "You clicked the headline!"; 
14 'headline' was used before it was defined. headline.innerHTML = "You clicked the headline!"; 
18 'alert' was used before it was defined. alert("Ive grabbed main heading"); 
20 Missing 'use strict' statement. alert("just about to call first function"); 
+2

你有id为 “mainHeading” HTML元素? – Snowmonkey

+0

发布您的标记。 – TheValyreanGroup

+0

复制并粘贴你的代码,将其作为jsfiddle运行:https://jsfiddle.net/snowMonkey/u7t7rcna/ - 它工作正常。 – Snowmonkey

回答

0

有没有元素与编号mainHeading因此headline == null

试图为属性null(如您对headline.onclick =所做的操作)分配一个值是一个错误,导致执行停止。

您可以通过运行代码例子说,看到这一点:

Uncaught TypeError: Cannot set property 'onclick' of null

+0

感谢您的回复。我有一个元素与Id mainHeading。我终于找到了我得到tracing.js的原因:19 Uncaught TypeError:无法设置属性'onclick'的空错误....这是因为我的脚本标记放在HTML标记之前,而不是AFTER。我在你之前的一篇文章中发现了这个问题\t 编辑于16年5月11日在22:29。谢谢 – Andy

0

把你相同的代码,创建与ID mainHeading元素,做工精细。见下文......

function firstFunction() { 
 
    secondFunction(); 
 
} 
 

 
function secondFunction() { 
 
    thirdFunction(); 
 
} 
 

 
function thirdFunction() { 
 
    fourthFunction(); 
 
} 
 

 
function fourthFunction() { 
 
    headline.innerHTML = "You clicked the headline!"; 
 
} 
 

 
var headline = document.getElementById("mainHeading"); 
 
alert("Ive grabbed main heading"); 
 
headline.onclick = function() { 
 
    alert("just about to call first function"); 
 
    firstFunction(); 
 
    alert("I've called first function"); 
 
};
<h2 id="mainHeading">Coo coo ka-choo</h2> 
 
<div id="content-pane"></div>