从 jQuery Mobile Selectmenu Widget 获取所选索引

Getting selected index from jQuery Mobile Selectmenu Widget

本文关键字:索引 获取 Widget jQuery Mobile Selectmenu      更新时间:2023-09-26

我在获取选择小部件的选定索引时遇到问题。这是 HTML

<div data-role="content" id="resultados">
    <label for="select-choice-0" class="select">Resultados:</label> 
    <select name="select-choice-0" id="listaResultados"></select>   
</div>

我以这种方式动态地向小部件添加选项(这有效):

$listaRe = $("#listaResultados");
$listaRe.html("");
for(i=0;i<results.length;i++){
    $listaRe.append("<option value='"+i+"'>"+results[i]+"</option>");
}       
// results is a predefined array

当我每次更改时尝试获取所选索引时,它总是打印"索引:0":

$listaRe.change(function(){
console.log("Index: "+$listaRe.selectedIndex);
});

我正在使用jQuery 1.8.1和jQuery Moble 1.2.0

谢谢!

这是一个简单的问题:-

  • $listaRe这里是jQuery对象
  • 并且 jQuery 对象没有像 selectedIndex 这样的属性

因此,您可以这样做:

$listaRe.on('change', function () {
    console.log("Index: " + $listaRe[0].selectedIndex);
});

演示:小提琴

或者这个:-

$listaRe.on('change', function () {
    console.log("Index: " + $listaRe.prop("selectedIndex"));
});

演示:小提琴

以解决此问题。

尝试使用.on方法。这是工作代码:

$('#resultados').on('change','#listaResultados',function(){
alert($('option:selected',$(this)).index());
});

在此处查看工作演示:http://jsfiddle.net/rhyC5/

考虑结果长度为 5:

 $(document).ready(function () {
        $listaRe = $("#listaResultados");
             $listaRe.html("");
                for (i = 0; i < 5; i++) {
                    $listaRe.append("<option value='" + i + "'>" + i + "</option>");
                }
                // results is a predefined array
              $listaRe.change(function () {
              console.log("Index: " + $listaRe.prop("selectedIndex"));
        });
 })