2013-06-29 43 views
1

在下面的html中,我想用$(this)遍歷DOM,但是我找不到一些問題。無法使用jquery ajax成功回調函數來遍歷dom

<div class="albumWrapper"> 
    <div class="album" id="test1"> 
     <div class="fadein"> 
      <img src="images/album/1_b.jpg" /> 
      <img src="images/album/2_b.jpg" /> 
     </div> 
     <div class="descWrapper"> 
      <h1> 
       <a href="1">Weddings</a> 
      </h1> 
      <div class="description"> 
       <span class="quotes">"</span>description 1<span class="quotes">"</span> 
      </div> 
     </div> 
    </div> 
    <div class="gallery"></div> 
    <div class="album" id="test1"> 
     <div class="fadein"> 
      <img src="images/album/1_b.jpg" /> 
      <img src="images/album/2_b.jpg" /> 
     </div> 
     <div class="descWrapper"> 
      <h1> 
       <a href="2">Weddings</a> 
      </h1> 
      <div class="description"> 
       <span class="quotes">"</span>description 2<span class="quotes">"</span> 
      </div> 
     </div> 
    </div> 
    <div class="gallery"></div> 
</div> 

這是我寫的jquery。但它似乎有一些問題,當我使用$(this)。 所以請別人幫我找到這個錯誤。這將有所幫助。

 $(".descWrapper h1 a ").on("click", function(e) { 
      e.preventDefault(); 
      $.ajax({ 
       url: 'ajaxify/gallery.php', 
       type: "get", 
       data: "id=" + $(this).attr('href'), 
       beforeSend: function() { 

       }, 
       success: function(data) { 
        $(this).parents(".album").next(".gallery").html(data); 
       }, 
       error: function(xhr, status, errorThrown) { 
        alert(); 
       } 
      }); 
     }); 
+1

你能解釋一下你想先辦? – LazerSharks

+0

您是否在成功函數中引用$(this)?這不是在另一個範圍內嗎?嘗試在preventDefault()之後立即定義一個變量「albums」並使用該變量 – Anorgan

+0

讓我檢查:) –

回答

1

使用上下文選項:

$(".descWrapper h1 a ").on("click", function (e) { 
    e.preventDefault(); 
    $.ajax({ 
     context:this, 
     url: 'ajaxify/gallery.php', 
     type: "get", 
     data: "id=" + $(this).attr('href'), 
     beforeSend: function() { 

     }, 
     success: function (data) { 
      //now 'this' here refers to the clicked link 
      $(this).parents(".album").next(".gallery").html(data); 
     }, 
     error: function (xhr, status, errorThrown) { 
      alert(); 
     } 
    }); 
}); 
+0

這是更清潔的解決方案謝謝:) –

+0

老問題,幫助我與一個不同的問題,但.parents()而不是.parent()給了我一個乾淨的解決方案。謝謝! – 2016-09-01 08:53:42

1

success功能this心不是正確的範圍,也不會成爲「.descWrapper H1一個」元素。所以設置this給一個變量前手和使用變量,而不是AJAX的this

$(".descWrapper h1 a ").on("click", function(e) { 
    var element = $(this); 
    e.preventDefault(); 
    $.ajax({ 
     url: 'ajaxify/gallery.php', 
     type: "get", 
     data: "id=" + $(this).attr('href'), 
     beforeSend: function() { 

     }, 
     success: function(data) { 
       element.parents(".album").next(".gallery").html(data); 
     }, 
     error: function(xhr, status, errorThrown) { 
      alert(); 
     } 
    }); 
});