【问题标题】:How to get the id dropdown list on click event如何获取点击事件的id下拉列表
【发布时间】:2013-07-22 04:12:59
【问题描述】:

这是我的 jspPage。

<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>    
<option id="2">Supervisor</option>
</select>

这里是javascript

 function Class(str)
{
    alert(str);
}

我想在 onchange 事件中获取 Option 的 id。谢谢:)

【问题讨论】:

  • 这个。我试图 id 是 1

标签: javascript html jsp


【解决方案1】:

如果您尝试获取已选择选项的 ID,则可以这样做

function Class(str)
{
    var select = document.getElementById("class_Teacher");
    var option = select.options[select.selectedIndex];
    alert(option.id);
}

【讨论】:

    【解决方案2】:

    您的 onchange 事件将如下所示。只需删除 .id,因为这将返回选择框本身的 id 而不是选项

    onchange="myFunction(this)"
    

    你的javascript函数像这样,它会提醒所选选项的ID

    function myFunction(ele){
       alert(ele.options[ele.selectedIndex].id);
    }
    

    分解ele 表示选择框(一个dom 对象)。 .options 访问选择框中的选项。 [] 括号是访问特定选项的一种方式。像数组myArr[1] 等,ele.selectedIndex 返回一个代表所选选项的数字,即如果选择了第一个选项 - ele.selectedIndex 将等效于 0

    【讨论】:

      【解决方案3】:

      HTML(你应该使用“value”属性而不是“id”)

      <select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
      <option id="1" value="ID1">Manager</option>    
      <option id="2" value="ID2">Supervisor</option>
      </select>
      

      JS

      var selectElement = document.getElementById("class_Teacher");
      selectElement.onchange=function(){
          alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
          alert(selectElement.selectedIndex);                           // index starting from 0
          alert(selectElement.value);                                   // value of the selected element
      };
      

      Fiddle

      【讨论】:

        【解决方案4】:

        使用GetElementByIDselsectedIndex属性

        <script>
            function val() {
                d = document.getElementById("select_id").selectedIndex;
            
                alert(d);
            }
            </script>
         <select onchange="val()" id="select_id">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-08
          • 1970-01-01
          • 2020-10-09
          • 1970-01-01
          • 1970-01-01
          • 2016-09-14
          相关资源
          最近更新 更多