2013-07-30 30 views
2

新的Bie:我有一個列表數據,使用json format從數據庫中獲取並顯示到列表視圖中。但我仍然混淆瞭如何獲得列表視圖的選定索引,這是我的代碼:如何獲得選定的索引JQuery Mobile Listview

<script> 
    function loadListTips(){ 
    $('#message').html('Loading...'); 
    $.ajax({ 
     type: 'get', 
     url: "http://10.0.2.2/compfest/ajax/belajar/list_tips.php", 
     success: function(response){ 
      var html = ''; 
      $.each(response, function(index,item){ 
       html += '<li>'; 
       html += '<a>'; 
       html += '<span class="judul">' + item.judul + '</span>'; 
       html += '</a>'; 
       html += '</li>'; 
      }); 
      $('#penyakit_list').html(html); 
      $('#penyakit_list').listview('refresh'); 
      $('#message').html(''); 
     }, 
     error: function(e){ 
      alert('Error: ' + e); 
     } 
    }); 
} 
</script> 

希望有人幫助我。

+0

「listview的選定索引」 - 你是什麼意思?你試圖在列表視圖中爲'a'標籤寫一個'click'事件嗎? – krishgopinath

+0

是的,我想嘗試如何編寫基於索引的列表視圖的點擊事件.. –

+0

任何需要使用索引?其實它有點不需要..爲什麼你需要索引? – krishgopinath

回答

4

您不需要li的選定索引來綁定click事件。您可以嘗試使用事件委派來綁定您的點擊事件。將點擊事件綁定到ul,並將其委託給li

$("#penyakit_list").on("click", "li a", function() { 
    //your code 
}); 

還有一個選擇是綁定點擊到document

$(document).on("click", "#penyakit_list li a", function() { 
    //your code 
}); 

要訪問索引,只要使用這個點擊事件中:

$(this).closest("li").index(); 

其中this是您剛剛點擊的a。所以現在你的點擊事件看起來是這樣的:

$(document).on("click", "#penyakit_list li a", function() { 
     alert($(this).closest("li").index()); // this will give the index of the li. You could store it in a variable and send it via ajax. 
}); 
+0

+1來自我,很好的答案 – Gajotres

1

+1去bundleofjoy!

我無法添加評論,因爲我的「聲望點」低於極限值添加評論。

我用這個答案alert($(this).closest("li").attr("id"));

有一個好的一天!