使用jQuery获取所选选项的索引

Val*_* Ru 161 html indexing jquery select

我对如何从HTML <select>项目中获取所选选项的索引感到有点困惑.

页面上有两种描述的方法.但是,两者都在回归-1.这是我的jQuery代码:

$(document).ready(function(){
    $("#dropDownMenuKategorie").change(function(){
        alert($("#dropDownMenuKategorie option:selected").index());
        alert($("select[name='dropDownMenuKategorie'] option:selected").index());
    });
});
Run Code Online (Sandbox Code Playgroud)

并在HTML中

(...)
<select id="dropDownMenuKategorie">
    <option value="gastronomie">Gastronomie</option>
    <option value="finanzen">Finanzen</option>
    <option value="lebensmittel">Lebensmittel</option>
    <option value="gewerbe">Gewerbe</option>
    <option value="shopping">Shopping</option>
    <option value="bildung">Bildung</option>
</select>
(...)
Run Code Online (Sandbox Code Playgroud)

为什么会这样?select在分配change()方法时,是否有可能没有"准备好" ?此外,换.index().val()的返回正确的值,所以这是混淆了我,甚至更多.

Guf*_*ffa 313

第一种方法似乎适用于我测试的浏览器,但选项标签并不真正对应所有浏览器中的实际元素,因此结果可能会有所不同.

只需使用selectedIndexDOM元素的属性:

alert($("#dropDownMenuKategorie")[0].selectedIndex);
Run Code Online (Sandbox Code Playgroud)

更新:

从版本1.6开始,jQuery具有prop可用于读取属性的方法:

alert($("#dropDownMenuKategorie").prop('selectedIndex'));
Run Code Online (Sandbox Code Playgroud)

  • @ Joan.bdm jquery没有`selectedIndex`属性.添加`[0]`将jquery对象转换为具有`selectedIndex`属性的javascript对象.没有`[0]`,这个例子不起作用 (33认同)
  • 为什么`[0]`? (6认同)

小智 94

以Jquery方式解决这个问题的好方法

$("#dropDownMenuKategorie option:selected").index()
Run Code Online (Sandbox Code Playgroud)

  • OP已经尝试过了.代码与问题中的第一个方法相同. (3认同)
  • 我喜欢这个答案不需要OP的首选答案的`[0]`,作为一个python dev,我真的很欣赏这个答案的可读性. (2认同)

小智 18

根据user167517的回答,我的解决方案略有不同.在我的函数中,我使用一个变量作为我所针对的选择框的id.

var vOptionSelect = "#productcodeSelect1";
Run Code Online (Sandbox Code Playgroud)

索引返回:

$(vOptionSelect).find(":selected").index();
Run Code Online (Sandbox Code Playgroud)


Nic*_*ord 16

您可以使用该.prop(propertyName)函数从jQuery对象的第一个元素获取属性.

var savedIndex = $(selectElement).prop('selectedIndex');
Run Code Online (Sandbox Code Playgroud)

这使您的代码保持在jQuery领域内,并避免使用选择器查找所选选项的其他选项.然后,您可以使用重载来恢复它:

$(selectElement).prop('selectedIndex', savedIndex);
Run Code Online (Sandbox Code Playgroud)


raj*_*wat 6

试试这个

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);
Run Code Online (Sandbox Code Playgroud)

  • jQuery不够 (7认同)
  • @Beanwah - 这是测试任何东西的最佳方式!;) (3认同)
  • @JoePC 不,不是。console.log() 会做得更好 (3认同)

Ris*_*tha 6

selectedIndex是一个JavaScript选择属性.对于jQuery,您可以使用以下代码:

jQuery(document).ready(function($) {
  $("#dropDownMenuKategorie").change(function() {
    // I personally prefer using console.log(), but if you want you can still go with the alert().
    console.log($(this).children('option:selected').index());
  });
});
Run Code Online (Sandbox Code Playgroud)