为什么此事件侦听器不工作

Why does this event listener not work?

本文关键字:工作 侦听器 事件 为什么      更新时间:2023-09-26

我尝试向cars3 id’d段落添加一个事件侦听器,这样当我单击该段落时,它应该执行getValue()方法,但它不起作用。我不明白为什么。谢谢

<!DOCTYPE html>
<html lang="en">
 <head>
<script>     
function getValue()
   {
        var x=document.getElementById("cars").value;
        document.getElementById("cars2").innerHTML = x.toString();
    }
document.getElementById("cars3").addEventListener("click", getValue());
</script>
</head>
<body>
<h1 id="myHeader" onclick="getValue()">"CLICk HERE !" </h1>
<p id="cars3">afaf</p>
 <select id="cars" name ="cars">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option></select> 
  </select>

<p id="cars2">afaf2</p>
</body>
</html>

去掉括号:

addEventListener("click", getValue());
//--------------------------------^^

制作:

addEventListener("click", getValue);

已编辑

同时将脚本标记移动到正文下方。您的代码没有等待页面呈现,因此document.getElementById("cars3")无法获取元素。

<body>
  ...
</body>
<script>
function getValue()
  ...
<script>

这对我来说很有效,你必须去掉函数的"()",并使用文档的事件加载,因为当你的addeventlistener第一次被调用时,html不存在,所以找不到cars3元素。

<!DOCTYPE html>
<html lang="en">
 <head>
<script>     
function getValue()
   {
        var x=document.getElementById("cars").value;
        document.getElementById("cars2").innerHTML = x.toString();
    }
window.onload = function() {
  document.getElementById("cars3").addEventListener("click", getValue);
};  

</script>
</head>
<body>
<h1 id="myHeader" onclick="getValue()">"CLICk HERE !" </h1>
<div id="cars3">afaf</div>
 <select id="cars" name ="cars">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option></select> 
  </select>

<p id="cars2">afaf2</p>
</body>
</html>