选择/option标签及其id

select/option tags and their id

本文关键字:id 标签 option 选择      更新时间:2023-09-26

我有许多select标签,当用户单击option标签之一时,我想获得select元素的id,其中单击了option

我该怎么做?

使用change事件:

document.querySelector('#mySelect').addEventListener('change', function() {
   console.log(this.value);
   console.log(this.id);
}, false);
<select id="mySelect">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

要将此扩展到多个元素,请在事件之外定义函数,遍历选择并将事件侦听器附加到它们:

function selectChange() {
   console.log(this.value);
   console.log(this.id);
}
var selects = document.querySelectorAll('select');
for (var i = 0; i < selects.length; i++) {
   selects[i].addEventListener('change', selectChange, false);
}
window.onload=function(){
 selects=document.getElememtsByTagName("select");
 for(i=0;i<selects.length;i++){
     selects[i].onchange=function(){
         var select=this.id;
         var value=this.value;
         var option=this.parentElement.id;
        //do whatever
        }
    }
}

简单的解决方法:

<select id="select1">
    <option id="o1">1</option>
    <option id="o2">2</option>
</select>
<select id="select2">
    <option id="o1">3</option>
    <option id="o2">4</option>
</select>
<select id="select3">
    <option id="o1">5</option>
    <option id="o2">6</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
window.onload=function()
{
    $(document).on("change","select",function(){
    alert($(this).attr("id"));
   })
}