我有以下代码,如果单击#test按钮,将在#currentActivities中生成内容。还有另一个#hide按钮,可以简单地隐藏#currentActivities的内容。我的问题是,如果我第一次点击#test,我可以获得内容。当我单击#hide时,可以按预期隐藏#currentActivities的内容。但是,如果再次单击#test,则无法生成内容。我试图在开头添加$('#currentActivities').empty();
,但似乎不起作用。任何人都可以帮助我并指出我的问题吗?
$("#test").click(function() {
$('#currentActivities').empty();
$.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "jsoncallback",
data: {
//some data here
},
url: "http://mydomain.com/check.php?jsoncallback=?",
success: function(data) {
$.each(data, function(index, student) {
$('#currentActivities').append(
'<li><a href="tutor_student_detail.html" data-name="' + data[index].data.NameA + '">' +
'<h4>' + data[index].data.NameA + '</h4>' +
'<p>' + data[index].data.NameA + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('name');
window.localStorage["Request"] = "true";
}); //end of li a
});
$('#load2').hide();
$('#filter').show();
$('#currentActivities').listview('refresh');
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
return false;
});
答案 0 :(得分:3)
您需要使用委托事件(aka live event)。因为您正在使用动态加载的DOM元素。
类似的东西:
$('body').on('click', '#test', function() {
// all code belong to click handler
});
有关使用.on()
see here 的委托事件绑定的更多信息。
注意:强>
而不是body
用户所有那些新加载和附加元素的静态容器。
由于你的问题是关于jquery mobile,所以我认为对于现场evnet委托你可以尝试类似的东西:
$('#test').live('click', function() {
// all codes belong to click hander
});
另一种方式是:
$(document).delegate('#test', 'click', function() {
// codes
});