2013-10-21 57 views
1

我在獲取選定構件的選定索引時遇到問題。這裏是從jQuery Mobile Selectmenu構件獲取選定索引

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

我動態添加選項的插件這樣的HTML(這工作):

$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 1.2.0 MOBLE

謝謝!

+1

它似乎結果是undefined –

回答

1

這是很簡單的問題: -

  • $listaRe這裏是一個jQuery對象
  • 和jQuery對象沒有財產如selectedIndex

因此,要麼你可以這樣做:

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

演示:Fiddle

或本: -

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

演示:Fiddle

來解決問題。

0

考慮結果的長度爲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")); 
     }); 
}) 
+0

我相信console.log(「Index:」+ $ listaRe.prop(「selectedIndex」));也會工作? – VJS

1

嘗試使用.on方法。這裏是工作代碼:

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

檢查這裏的工作演示:http://jsfiddle.net/rhyC5/

+1

很好解釋。 +1 – VJS

相關問題