选择选项元素时触发事件(无jQuery)

时间:2018-03-09 21:57:24

标签: javascript

这个问题已被多次询问,但我见过的所有答案都使用了jQuery,我可以将其用于此项目。我试图在选项元素"其他"已从select元素中的列表中选择。

使用"更改"因为事件似乎不起作用。



document.querySelector("#title").addEventListener("change", (event) => {
  if (event.target.textContent === "Other") {
    console.log("Other Selected");
  }
});

<select id="title" name="movie_title">
    <option value="titanic">Titanic</option>
    <option value="avatar">Avatar</option>
    <option value="other">Other</option>
</select>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

您可以使用每次更改选项时触发的onchange事件:

&#13;
&#13;
function myfunction(value) {
  console.log("changed to "+value+"!")
}
&#13;
<select onchange="myfunction(this.value)" id="title" name="movie_title">
   <option value="titanic">Titanic</option>
   <option value="avatar">Avatar</option>
   <option value="other">Other</option>
</select>
&#13;
&#13;
&#13;

另一个解决方案可能是添加event listener

document.getElementById("title").addEventListener("change", (event) => {
  // run your code
});

&#13;
&#13;
document.getElementById("title").addEventListener("change", (event) => {
  console.log("changed to: " + event.target.value + "!");
});
&#13;
<select id="title" name="movie_title">
   <option value="titanic">Titanic</option>
   <option value="avatar">Avatar</option>
   <option value="other">Other</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用event.target.value

document.getElementById("title").addEventListener("change", (event) => {
  console.log(event.target.value);
});
<select id="title" name="movie_title">
       <option value="titanic">Titanic</option>
       <option value="avatar">Avatar</option>
       <option value="other">Other</option>
    </select>

答案 2 :(得分:0)

要达到预期的结果,请使用event.target.value,而不是textContent,它将提供所有选项而不是选定的选项

document.querySelector("#title").addEventListener("change", (event) => {
  if (event.target.value === "other") {
    console.log("Other Selected");
  }
});

代码示例 - https://codepen.io/nagasai/pen/JLoNMK?editors=1010

相关问题