0

我有以下代码,如果单击#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;
});
4

1 回答 1

3

您需要使用委托事件(又名实时事件)。因为您正在使用动态加载的 DOM 元素。

就像是:

$('body').on('click', '#test', function() {

   // all code belong to click handler

});

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

笔记:

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

由于您的问题是在 jquery mobile 上,所以我认为对于实时 evnet 委托,您可以尝试以下操作:

$('#test').live('click', function() {

 // all codes belong to click hander

});

另一种方法是:

$(document).delegate('#test', 'click', function() {

  // codes

});
于 2013-03-19T19:50:25.773 回答