关于.append()和.empty()的问题

Problems on .append() and .empty()

本文关键字:问题 empty 关于 append      更新时间:2023-09-26

我有下面的代码,如果#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;
});

你需要使用delegate event(又名live event)。因为你正在处理一个动态加载的DOM元素。

类似:

$('body').on('click', '#test', function() {
   // all code belong to click handler
});

有关使用.on() 绑定委托事件的更多信息,请参阅此处

注意:

代替body用户任何静态容器的所有新加载和附加的元素。

你的问题是关于移动版jquery的所以我认为对于实时事件委托你可以尝试这样做:

$('#test').live('click', function() {
 // all codes belong to click hander
});

,另一种方式是:

$(document).delegate('#test', 'click', function() {
  // codes
});