首页 > 解决方案 > 如果 HTML 选择器具有特定值,如何运行 Java Script 函数?

问题描述

所以我有一个非常基本的 HTML 表单,我试图弄清楚如果用户在 HTML 元素内选择具有特定值的特定元素,如何运行 JS 函数。我对编码非常非常陌生,如果看起来很糟糕,请原谅我;但是这样的事情,当我选择具有“两个”的选项时,我想让背景变成红色:

HTML:

<select id="numberDropdown">
  <option disabled selected>0</option>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
</select> 

JavaScript:

   document.getElementById("numberDropdown").value = document.getElementById("numberDropdown").selectedIndex.value;
   if (document.getElementById("numberDropdown").value = "two"){
       document.body.style.backgroundColor = "red";
    };

我真的不知道任何 java 脚本,只是尝试输入一些内容以便您理解问题。谢谢你的帮助!

标签: javascripthtmlformsdomselectedindex

解决方案


每次选择新值时都应该更新

const selectElement = document.getElementById("numberDropdown");

selectElement.addEventListener('change', (event) => {
  let val = selectElement.options[selectElement.selectedIndex].value;
  if (val == "two"){
      document.body.style.backgroundColor = "red";
  }
});

推荐阅读