开发者问题收集

Javascript:未捕获的类型错误:无法在 HTMLButtonElement.but.onclick 处设置 null 的属性“innerHTML”(

2017-05-29
1223

我试图让每次点击随机按钮时,都会显示一个新的 div 的内部 HTML - 但是我在 Javascript 控制台中收到错误消息“无法设置属性”。有人能解释一下这是什么意思以及我做了什么导致它吗?

<h1>Test</h1>

<div id="quote1">this is quote number 1</div>

<p id="quote 2">this is quote number 2</p>

<div id="quote 3">this is quote number 3</div>

<button id="button1">Randomise</button>



<script type="text/javascript">

var but = document.getElementById('button1');
but.onclick = function() {
document.getElementById("quote1").innerHTML = "hi";
document.getElementById("quote2").innerHTML =  "ho";

}
2个回答

因为 id 是 quote 2 而不是 quote2 ,也就是说,在 quote 2quote 3 之间有多余的空格

更改为

<p id="quote2">this is quote number 2</p>
<h1>Test</h1>

<div id="quote1">this is quote number 1</div>

<p id="quote2">this is quote number 2</p>

<div id="quote3">this is quote number 3</div>

<button id="button1">Randomise</button>



<script type="text/javascript">

var but = document.getElementById('button1');
but.onclick = function() {
document.getElementById("quote1").innerHTML = "hi";
document.getElementById("quote2").innerHTML =  "ho";

} 
</script>
Shubham Khatri
2017-05-29
<h1>Test</h1>

<div id="quote1">this is quote number 1</div>

<p id="quote2">this is quote number 2</p>

<div id="quote3">this is quote number 3</div>

<button id="button1">Randomise</button>



<script type="text/javascript">

    var but = document.getElementById('button1');
    but.onclick = function() {
            document.getElementById("quote1").innerHTML = "hi";
            document.getElementById("quote2").innerHTML =  "ho";

        }
    </script>
2017-05-29