2012-10-30 69 views
0

我想用class dialogBody清空div的内容,然后追加返回的ajax响应。请参阅下面的代码。我遇到的问题是.html(响应)不会执行任何操作,因为单击的元素将被删除。点击元素被移除后,如何继承$ this.closest('。dialogBody')的目标元素?jquery这个选择器被点击元素删除后

<div class="dialogBody"> 
    <p>Some content<a href="/question/33" class="ajaxReplace">Click to show question</a></p> 
</div> 
<script> 
$(".ajaxReplace").live("click", function(e){ 
    e.preventDefault(); 
    var $this = $(this); 
    $this.closest('.dialogBody').empty();   
    ajaxUrl = $(this).attr("href")+"?ajax=1"; 
    $.ajax({ 
    type: "POST", 
    url: ajaxUrl, 
    success: function(response){   
     $this.closest('.dialogBody').html(response); 
     console.log(response); 
    } 
    })     
}); 
</script> 

回答

4

它赋值给一个变量:

$(".ajaxReplace").live("click", function(e){ 
    e.preventDefault(); 
    var $this = $(this); 
    var $dBody = $this.closest('.dialogBody').empty(); // <------  
    ajaxUrl = $(this).attr("href")+"?ajax=1"; 
    $.ajax({ 
    type: "POST", 
    url: ajaxUrl, 
    success: function(response){   
     $dBody.html(response); // <------ 
     console.log(response); 
    } 
    })     
}); 
2

保存到元素的引用您需要,而不是保存到元素的引用将被删除的:

$(".ajaxReplace").live("click", function(e){ 
    e.preventDefault(); 
    var ajaxUrl = $(this).attr("href")+"?ajax=1", 
     $thisDialog = $(this).closest('.dialogBody').empty();   
    $.ajax({ 
    type: "POST", 
    url: ajaxUrl, 
    success: function(response){   
     $thisDialog.html(response); 
     console.log(response); 
    } 
    })     
}); 

你” d还需要将ajaxUrl赋值移动到之前您删除了this元素。

相关问题