2013-07-30 28 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"));

有一个好的一天!