有人能告诉我为什么我的点击事件不起作用吗?

时间:2018-05-16 06:44:05

标签: javascript html

在控制台中获取类型错误:

  

未捕获的TypeError:无法读取null

的属性'addEventListener'

点击“点击”按钮后。我该如何解决这个问题?

document.getElementById("btn").addEventListener("click", function(){
  document.getElementById("para").innerHTML("This is text");
});
<ul id="myList">
  <li>item1</li>
  <li>item 2</li>
</ul>
<button id="btn">Click </button>
<form name="myForm">
  Select output mode: <input type="radio" name="output" value="printer" checked /> Printer
  <input type="radio" name="output" value="scanner" /> Scanner
</form>

1 个答案:

答案 0 :(得分:0)

您需要使用document.getElementById("para").innerHTML = "This is text";,因为innerHTML不是函数,而是getElementById()的属性。

document.getElementById("btn").addEventListener("click", function(){
    document.getElementById("para").innerHTML = "This is text";
})
<p id="para"> </p>
<ul id="myList">

    <li>item1</li>
    <li>item 2</li>
</ul>
<button id="btn">Click </button>
<form name="myForm">
    Select output mode: <input type="radio" name="output" value="printer" checked /> Printer
    <input type="radio" name="output" value="scanner" /> Scanner

</form>