2012-02-07 70 views
1

我已經在這裏搜索了一段時間,找不到一個簡單問題的具體答案。Jquery AJAX方法

我有一些生成的HTML,其中包含指向服務器上可能存在或可能不存在的文件的鏈接。生成器不知道文件是否存在,因此它假定它們存在。

我想使用JQ AJAX方法檢查損壞的href和hide()鏈接,如果該文件不存在,應該足夠簡單,我認爲。

<tr> 
    <td>24</td> 
    <td>201106</td> 
    <td>PRODID</td> 
    <td>ABC</td> 
    <td>98</td> 
    <td>40.95</td> 
    <td>4013.1</td> 
    <td>15.56365</td> 
    <td>2487.8623</td> 
    <td>61.99</td> 
</tr> 
<tr> 
    <td colspan="9" style="border-top:#047D66 solid 1px; background-color:#e0e0e0; border-bottom:#047D66 solid 1px"><br></td> 
    <td><a href="http://dashboards/wrappedstuff_uk/files/PRODID.pdf" id="checklnk">PDF</a></td> 
</tr> 

我的jQuery腳本

$.ajax({ 
    url: $('#checklnk').attr('href'), 
    type: 'text', 
    method: 'HEAD', 
    error: function() { 
     $(this).hide(); 
    }, 
    success: function(){ 
     $(this).css('background-image',url('/dashboards/cms/intra/images/icon-link-pdf.png')); 
    } 
}); 

鏈接不隱藏,我懷疑問題可能是$(this)不是DOM元素我的期望。

任何人都喜歡指向正確的方向。

+0

你什麼時候運行該代碼?在DOM準備好的循環中?當用戶點擊一個元素? – 2012-02-07 09:56:05

+0

你有更多的標籤嗎?如果你應該使用類。 – 2012-02-07 09:58:01

+0

表格如何與您的#checklink相關?這裏需要更多的解釋。 – 2012-02-07 10:00:30

回答

0

你猜對了$(this)不是指href,你將需要使用元素id來做你的東西。這樣

$("#checklnk").hide(); 

OR

檢查一番在一個網頁上的所有錨標籤出手

$("a").each(function(i){ 
     $.ajax({ 
      url: $(this).attr('href'), 
      type: 'text', 
      method: 'HEAD', 
      error: function() { 
       $(this).hide(); 
      }, 
      success: function(){ 
       $(this).css('background-image',url('/dashboards/cms/intra/images/icon-link-pdf.png')); 
      } 
     });   
    }); 

希望這有助於。

+0

現在我明白了。謝謝大家。 – 2012-02-07 10:27:30

0
$.ajax({ 
    url:$('#checklnk').attr('href'), 
    type: 'text', 
    method: 'HEAD', 
    error: function() { 
    $("#checklnk").hide(); 
    }, 
    success: function(){ 
    $("#checklnk").css('background-image',url('/dashboards/cms/intra/images/icon-link-pdf.png')); 
    } 

成功和錯誤的異步方法。所以你必須再次使用選擇器

0

我建議你在做AJAX呼叫之前將你的$(this)保存到一個變量中。所以你有權訪問你指定的鏈接,並且能夠訪問.hide(), .show()。此外,如果你的html頁面中有更多的a元素,你應該使用類而不是id!短舉例:

var myAnchor=$(this); 

$.ajax({ 
    // run your code here. 
});