跟踪和调试JS代码

时间:2017-01-12 14:14:53

标签: javascript html

在特定网站上的启动器教程和演示者代码工作后,但我的没有。 (我相信我们有完全相同的代码)。他的代码执行到警报框“即将调用第一个函数”的位置。但是我的代码没有达到那一点。我错过了什么吗?

我的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 个答案:

答案 0 :(得分:0)

没有标识为mainHeading的元素headline == null

尝试为null属性赋值(与headline.onclick =一样)是一个错误,导致执行暂停。

您可以通过运行代码示例来看到:

  

未捕获的TypeError:无法设置属性'onclick'为null

答案 1 :(得分:0)

使用相同的代码,使用ID mainHeading创建一个元素,工作正常。见下文......

&#13;
&#13;
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");
};
&#13;
<h2 id="mainHeading">Coo coo ka-choo</h2>
<div id="content-pane"></div>
&#13;
&#13;
&#13;