我有很多select
个代码,当用户点击其中一个option
代码时,我想获得id
个select
元素,点击{{1} }}
我怎么能这样做?
答案 0 :(得分:2)
使用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>
&#13;
要为多个元素缩放此值,请在事件之外定义函数,迭代您的选择并将事件侦听器附加到它们:
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);
}
答案 1 :(得分:2)
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
}
}
}
答案 2 :(得分:0)
简易解决方法:
<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"));
})
}