2013-01-07 21 views
0

我有以下jQuery代碼,它不工作,因爲我期望它。我確信我做錯了什麼,但我沒有看到它。基本上,如果博客不發佈,當我點擊圖片時,它訪問我的數據庫並相應地更新它。所有這一切都很好。jQuery多個值更新問題

  1. 我點擊.not_published
  2. .not_published與圖像標記,顯示Ajax的loader.gif
  3. 當服務器返回一個成功消息改變的內容,我更新#not_published的HTML父母的新內容包括使用.published替換.not_published。

Blog Post List

我得到的,當我點擊.not_published是AJAX圖像加載,並在那裏停留。如果我在成功函數內添加一個alert("message');,它可以正常工作。

Loading Image

列表點3不起作用。我無法弄清楚爲什麼。請看下面的代碼:

jQuery代碼:

$(document).on('click','.not_published', function(){ 
     var ID = $(this).siblings("p").text(); 
     $(this).html("<img style=\"padding-left:15px;\" src=\"/img/admin/ajax-loader.gif\">"); 
     $.ajax({ 
      url: "/posts/publish/"+ID, 
      type: "post", 
      data: '', 
      success: function(responseText, statusText, xhr, $form){ 
       $(this).parent().html("<span class=\"published\"><img style=\"width:20px;\" src=\"/img/admin/checkmark_green.png\"></span><p style=\"display: none\">ID</p>"); 
      }, 
      error: function(responseText){ 
       alert(responseText); 
      } 
     }); 
}); 

HTML代碼

<div id="publish"> 
    <span id="not_published"> 
     <img style="width:20px" src="/img/admin/checkmark_red.png"> 
    </span>" 
    <p style="display: none">1</p> 
</div> 
+0

你爲什麼要通過AJAX加載圖像注意到並沒有直接加載,只是更改源?還有爲什麼你應該改變ID,當你可以改變具有相同效果的類時。該ID「必須」是唯一的才能正常工作。嘗試HADI的解決方案 – Vogel612

+0

ID必須是唯一的。使用類 – Popnoodles

回答

1

存儲元素在AJAX請求的變量外之前,但你這樣做......成功處理程序內之前登錄this安慰。這不是你想象的那樣。

也改變ID,以班爲在評論

$(document).on('click','.not_published', function(){ 
     var ID = $(this).siblings("p").text(); 
     var $el=$(this).html("<img style=\"padding-left:15px;\" src=\"/img/admin/ajax-loader.gif\">"); 

     $.ajax({ 
      url: "/posts/publish/"+ID, 
      type: "post", 
      data: '', 
      success: function(responseText, statusText, xhr, $form){ 
       /* change $(this) to $el defined above*/ 
       $el.parent().html("<span class=\"published\"><img style=\"width:20px;\" src=\"/img/admin/checkmark_green.png\"></span><p style=\"display: none\">ID</p>"); 
      }, 
      error: function(responseText){ 
       alert(responseText); 
      } 
     }); 
}); 
+0

非常感謝您的幫助。我在'$ .ajax'調用之前創建了'var publish = $(this)',並且在'success:function('裏面使用'publish.parent()。html('),並且它工作得很好。 –

+0

關於'this '在阿賈克斯請求..在那裏做了! – charlietfl

+0

是的......絕對.... –

3

您正在使用的ID #publish和#not_published。嘗試使用類,而不是使用多個#not_published像.not_published

,並檢查VAR ID發送

+0

我已經改變了一切類和仍然是相同的問題...我已經更新了我的問題與你所建議的 –

+0

更改我的問題ID是正確的值發送到適當的頁面? – HADI

+0

ID的值是正確的。我做了警報(ID),它是正確的。 –