我在表单中有一个选择(下拉列表)。当我更改下拉列表中的值时,我需要找出我是选择下拉列表中的第一个元素还是下拉列表中的第二个元素?
我们如何使用jQuery或JavaScript实现这一目标。
感谢您的时间。我一直在寻找,但在这方面找不到任何东西。
答案 0 :(得分:2)
您可以使用index()
方法:
var index = $("select option:selected").index();
答案 1 :(得分:2)
您可以使用index()
:
$("select").change(function() {
var selectedIndex = $("option:selected", this).index();
});
或者您可以使用普通的javascript selectedIndex
属性:
$("select").change(function() {
var selectedIndex = this.selectedIndex;
});
就我个人而言,我会使用后者,因为在可能的情况下使用本机javaScript结构会更好(并且速度稍快一些),尽管两者都会给你相同的结果。
答案 2 :(得分:0)
你可以;
var isFirst = $("#myselect").prop("selectedIndex") == "0";
答案 3 :(得分:0)
尝试以下jQuery脚本:
$("select").change(function() {
var optionselected = $(this).find("option:selected").index();
alert(optionselected);
});