【问题标题】:JQuery .load() makes content not clickable after loadJQuery .load() 使内容在加载后不可点击
【发布时间】:2012-01-25 19:56:53
【问题描述】:

我有一个页面,其中有一个 div。来自该 div 的内容由包含页面填充,并且该包含页面正在调用数据库以检索内容。

当用户单击“添加任务”按钮时,将进行 ajax 调用以将内容插入数据库,并使用 .load() 刷新显示所有任务的 div。 “删除任务”也会发生同样的过程;进行另一个 ajax 调用,从数据库中删除一行,并使用 .load() 刷新 div。

我在我的数据库表中看到了插入和删除,但前端有点不稳定。当页面首次加载时,我可以执行无限数量的“添加”操作,所有新任务都会显示在 div 中。但是,我只能执行一个“删除”操作;第一次尝试后,我似乎无法从 div 中选择一个元素。

这是“添加”代码:

$("#accept_new_task").click(function(){
    jQuery.ajaxSetup({async: false});

    //Make ajax call
    $.post("[url]", { [data] },

        //If successful, add a new item to task list and clear input
        function(data) {

            //Clear input
            $("#new_task_name").val('');
            $("#new_task_description").val('');

            //Show new task
            $('#newly_added_tasks').load('[page on server]', function() {
            });             



        });

    jQuery.ajaxSetup({async: true});    
});

还有“删除”代码:

//Deletes recently added task
$(".newtask").click(function(){
    alert('!');  //to test
    var val = $(this).attr('value');

    jQuery.ajaxSetup({async: false});

    //Make ajax call
    $.post("[url]", { [data] },

        //If successful, refresh div 
        function(data) {
            $('#newly_added_tasks').load('[page on server]', function() {
                alert('Load was performed.');
            });                             
        });     

    jQuery.ajaxSetup({async: true});  

});

正在加载的内容是使用从数据库调用中提取的内容生成的表格。这是一个sn-p:

<td>'.$task[$i]['name'].'</td>
<td>'.$task[$i]['description'].'</td>
<td><input type="button" class="newtask" name="accept_new_task" id="task_'.$task[$i]['task_id'].'" value="'.$task[$i]['task_id'].'"></td>

任何帮助将不胜感激。

【问题讨论】:

标签: jquery jquery-selectors jquery-load


【解决方案1】:

jQuery .click 事件不是实时事件,因此它只会使分配给它的项目可点击。一旦这些项目被刷新、移除或新项目进来,刷新的项目不会有点击事件,新项目不会有点击事件。

您需要使用jQuery .on 事件,它是 .live 事件的替代品。这样当内容刷新时,它们仍然会附加一个点击事件。

另一种选择是在内容刷新时分配点击事件。

【讨论】:

    【解决方案2】:

    改变这一行

    $(".newtask").click(function(){
    

    $(document).on(".newtask","click",function(){
    

    或使用委托

    $(document).delegate("click",".newtask",function(){
    

    原因是动态添加的元素不会附加到事件处理程序上,如果您使用的是 jQuery 1.7+,请使用 on,否则使用 delegate

    【讨论】:

      【解决方案3】:

      它适用于这个

      $(document).on("click",".newtask",function(){
      

      $(document).delegate(".newtask","click",function(){
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多