Javascript <;选择>;获取所选选项编号

Javascript <;选择>;获取所选选项编号,javascript,jquery,Javascript,Jquery,因此,我有一个带有选项的,但是当我选择一个选项来获取选项号时,我想要的是什么 我不希望他抓住属性(无值和文本)。因为它是动态的 示例: <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> <

因此,我有一个带有选项的
,但是当我选择一个选项来获取选项号时,我想要的是什么

我不希望他抓住属性(无值和文本)。因为它是动态的

示例:

<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>

苹果
梨
香蕉
橙色
当我选择Apple时,我会得到一个响应1。梨也是这样:2。等等

我发现:,但这将显示有多少选项可用

这里的人有什么解决方案

$('#mySelect').change(function(){
    $(#mySelect option).each(function(index){
        if ($(this).attr('selected') {
            console.log(index);
        }
    });
})
根据您的查询版本,您可能必须将.attr()改为.prop()

也可以使用

$('#mySelect').change(function(){
    $("#mySelect option").index($("#mySelect option:selected"))
})
根据您的查询版本,您可能必须将.attr()改为.prop()

也可以使用

$('#mySelect').change(function(){
    $("#mySelect option").index($("#mySelect option:selected"))
})

您可以使用
selectedIndex
属性

$(“#mySelect”).change(函数(){
console.log(“所选选项为”+此.selectedIndex);
})

选择一种水果
苹果
梨
香蕉
橙色

您可以使用
selectedIndex
属性

$(“#mySelect”).change(函数(){
console.log(“所选选项为”+此.selectedIndex);
})

选择一种水果
苹果
梨
香蕉
橙色

您可以使用纯JavaScript尝试以下操作:

document.addEventListener('DOMContentLoaded',function(){
var selectEle=document.getElementById('mySelect');
选择ele.addEventListener('change',函数(项目){
console.log(selectEle.selectedIndex+1);
});
});

苹果
梨
香蕉
橙色

您可以使用纯JavaScript尝试以下操作:

document.addEventListener('DOMContentLoaded',function(){
var selectEle=document.getElementById('mySelect');
选择ele.addEventListener('change',函数(项目){
console.log(selectEle.selectedIndex+1);
});
});

苹果
梨
香蕉
橙色

为什么不为每个选项指定一个值?您不想这样做的原因是什么?
selectedIndex
属性包含选项编号。
$('option:selected')。index()
为什么不为每个选项指定一个值?您不想这样做的原因是什么?
selectedIndex
属性包含选项编号。
$('option:selected').index()
为什么不使用
$(“\mySelect option:selected”)
而不是循环?每个
都可以直接使用
$('option:selected',this)。index()
为什么不使用
$(“#mySelect option:selected”)
而不是循环?而不是
。每个
都可以直接使用
$('option:selected',this)。index()
这一个很完美,因为它以0开头。谢谢。@jurdekker你在问题中没有要求以1开头吗?是的,但很抱歉。我忘了。这一个以1开头,因为
0
是一个选项,意味着他们没有选择任何内容。但是如果你去掉它,你可以轻松地添加1。这一个很完美,因为它以0开头。tha谢谢你。@jurdekker你在问题中没有要求以1开头吗?是的,但很抱歉。我忘了。这是以1开头的,因为
0
是一个选项,意味着他们没有选择任何内容。但是如果你去掉它,你可以轻松地添加1。