我必须将click事件添加到动态列表视图中。当我单击此列表时,它将重定向到更多详细信息页面。我正在获取特定区域的可用酒店列表,并将其插入列表视图。现在,当我单击任何特定列表时,酒店将重定向到更多详细信息页面。
查看以下可用酒店列表的图像列表视图。每个酒店都有唯一的ID,因此,当我单击任何列表时,它将使用该唯一的酒店ID,并从服务器中获取该酒店的更多详细信息,并显示在该酒店的专用页面上。我的问题是,如何甚至在动态列表视图上添加点击并传递唯一的酒店ID,以便以后可以使用该酒店ID从服务器中获取更多信息。
我的脚本代码,如何甚至在动态列表中添加点击
<script>
$(document).ready(function(){
$("#btnReg").click(function(){
$("#listHotelsOptions").empty();
var distance = document.getElementById('distance_id').value;
var output="";
var hiddenId="";
$.ajax({
url:"http://192.168.1.4/Experiements/webservices/getHotels.php",
type:"GET",
dataType:"json",
data:{type:"login", Distance:distance},
ContentType:"application/json",
success: function(response){
console.log(response)
$.each(response, function(index,value){
hiddenId+='<li type="hidden">'+value.Hotel.Id+'</li>';
output+='<li ><a href="#" style="text-decoration:none;"> <img alt="chef" src="./images/chef.min.png" width="20px" height="20px" >'+value.Hotel.Name+' has'+value.Hotel.Romms+'</a></li>';
});
$("#listHotelsOption").append(output).listview().listview('refresh');
},
error: function(err){
alert(JSON.stringify(err));
}
}) //ajax
}); //click
}); //ready
</script>
最佳答案
代替2个LI元素,将酒店ID保存为可见LI的data-attribute:
$.each(response, function(index,value){
output+='<li data-hotelid="'+value.Hotel.Id+'"><a href="#" style="text-decoration:none;"> <img alt="chef" src="./images/chef.min.png" width="20px" height="20px" >'+value.Hotel.Name+' has'+value.Hotel.Romms+'</a></li>';
});
而不是jQuery Mobile中的
$(document).ready(function(){
,您应该使用页面事件之一,例如页面创建。在页面创建时,使用event delegation为所有LI创建一个单击处理程序,以便包括动态创建的。使用jQM方法jqmData()从LI检索id数据属性:$(document).on("pagecreate", "#yourpageid", function(){
$("#listHotelsOption").on("click", "li", function(){
//get hotel id
var id = $(this).jqmData("hotelid");
... rest of click handler
});
$("#btnReg").on("click", function(){
//your code to dynamically create list
});
});
这是工作中的DEMO