繁体   English   中英

当我在HTML文件中编写脚本时,它可以工作,当我将相同的代码放在js文件中并链接时,它不起作用吗?

[英]When I write the script in HTML file it works, when I put the same code in a js-file and link it it does not work?

我在编程中遇到了一个新问题。 我正在尝试创建测验,并且我已经在html文件中编写了一个脚本,它可以完美运行。 但是,我想将脚本与html文件分开,因此我将脚本代码放入js文档并将其链接到索引文件。 根据我在执行此操作时的早期经验,它始终无需更改就可以正常工作。 但是,现在我收到一条错误消息,提示未定义功能checkAnswer !? 即使它写在js文档中。 以下是一些代码。

function _(x) {
    return document.getElementById(x);
    }

function renderQuestion() {
    test = _("test1");

    if(pos >= questions.length){
test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
_("testStatus").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
    _("testStatus").innerHTML = "Question " + (pos + 1)+ "of " + questions.length;
    question = questions[pos][0];
    chA = questions[pos][1];
    chB = questions[pos][2];
    chC = questions[pos][3];
    test.innerHTML = question + "<br>";
    test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
    test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
    }

    function checkAnswer() {
    choices = document.getElementsByName("choices");
for(var i=0; i<choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice == questions[pos][4]){
correct++;
}
pos++;
renderQuestion();
}

当我在控制台中查看时,下一行似乎出了点问题,但是我不知道该如何解决。 当我按下提交答案按钮时,我收到错误消息。

test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";

提前致谢!

这是我的小提琴的链接: http : //jsfiddle.net/zs860fLx/2/

我收到的错误消息是index.html第1行上的“ checkAnswer未定义”。

您必须初始化您的功能。 用纯JavaScript做到这一点的最简单方法是在您的body结束标记之前的底部,向HTML文件中添加一个init函数。

 init = function() { doSomething(); }; doSomething = function() { console.log("yes"); } 
 <body> <button onclick="doSomething()">click me</button> <script> (function() { init(); })(); </script> </body> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM