如何为事件监听器设置函数

时间:2019-05-06 20:51:12

标签: javascript dom

我具有此功能displaySelectedUser,因此我想仅使用DOM Selector API将displaySelectedUser设置为<select></select> UI元素的更改事件侦听器。

这是我尝试过的代码:

<body>
<div class="select">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
};
    document.querySelector('select').change = displaySelectedUser;   
  };
</script>

3 个答案:

答案 0 :(得分:1)

使用HTML5选择器API尝试此操作。

 document.querySelector(".select").addEventListener("change", displaySelectedUser)

答案 1 :(得分:0)

您只需在直接调用该函数的select元素上添加onChange事件处理程序即可。

<body>
<div class="select" onChange="displaySelectedUser()">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
};
</script>

答案 2 :(得分:0)

正如Tim所提到的,您只需在代码中添加 onchange 而不是 change 即可。

<body>
<div class="select">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
     alert('calling')
};
      const powerupTheUI = () => {
    document.querySelector('select').onchange = displaySelectedUser;   
  };
  
  powerupTheUI();
</script>