在外部.js文件中未检测到HTML元素

时间:2018-07-15 03:26:32

标签: javascript html frontend

我的HTML代码:

<div class="container">
<div class="question-card">
    <h1 id="question1">This is the question</h1>
</div>
<div class="answer-choices">
    <div class="row1">
        <span class="choice1" id="one" onclick="choice1()">One</span>
        <span class="choice2" onclick="choice2()">Two</span>
    </div>
    <div class="row2">
        <span class="choice3" onclick="choice3()">Three</span>
        <span class="choice4" onclick="choice4()">Four</span>
    </div>      
</div>
<button id="btn" onclick="next()">Next</button>

我的js代码:

function clickNextText(){
    document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}   //This is working fine


var str
element = document.getElementById('btn'); 
if (element != null) {
 str = element.value;
}
else {
      str = null;
}
console.log(str)  //This is however returning null. 

我不明白这里出了什么问题。而且,没有检测到div之后带有类选择选项的每个ID为id的元素。将脚本代码放在.html本身时,效果很好。

2 个答案:

答案 0 :(得分:0)

很可能您的JavaScript在页面加载之前就已在运行。尝试将整个javascript逻辑包装在一个函数中,然后在window.load上运行。

window.load = function () {
// your code here
}

答案 1 :(得分:0)

首先在单击时将功能名称从next()更改为clickNextText()

<button id="btn" onclick="clickNextText();">Next</button>

然后在javascript中使用此代码,而不是:

function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}  

document.onload = function(){
var str
element = document.getElementById('btn'); 
if (element != null) {
   str = element.value;
}
else {
   str = null;
}
console.log(str);
};