2013-02-12 42 views
0

我需要根據href是否包含文本鏈接或圖像鏈接來編寫if語句。所以,如果我得到這樣的鏈接的內容:確定鏈接是文本還是圖像

jQuery(document).ready(function($){ 
    $('a').click(function(event) { 
    var $linkContent = $(this).html(); 
    // this doesnt work.. just one of the things I tried 
    // var imgsrc = $(this).attr('src'); 
     }); 

    }) 

我還以爲我可以走另一條路,只是獲取文本內容,如:

var linkContent = $(this).text(); 

後來,當我提醒這個變量它顯示文本鏈接的文本,圖像空白。大!但仍然沒有爲我工作。我打算基於.length編寫規則,但如果提醒長度,圖像鏈接仍然會給我一個整數,即使提醒.text()也是空白。我很困惑!

回答

2

this在您的點擊處理程序中將始終是一個錨點元素,因爲它已附加到代碼中的錨點元素。但只是做

$('a').click(function(event) { 
    var $this = $(this); 
    if($this.find("img").length) { //searches within the anchor element for an img element 
     //it's an image 
    } else { 
     //no images in the anchor tag 
    } 
}) 
+0

確認!這麼容易,(這)總是讓我沮喪。謝謝謝謝! – Zac 2013-02-12 20:08:36

-4

您應該使用HTTP HEAD來查看內容上下文。

這裏是你可以從剪斷位的樣品,它被用來作爲一個檢查,看是否有網址存在與否:

public static boolean exists(String URLName){ 
try { 
    HttpURLConnection.setFollowRedirects(false); 
    // note : you may also need 
    //  HttpURLConnection.setInstanceFollowRedirects(false) 
    HttpURLConnection con = 
    (HttpURLConnection) new URL(URLName).openConnection(); 
    con.setRequestMethod("HEAD"); 
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
    return false; 
} 

}

+0

問題是關於jQuery。這當然不是Javascript,因此不是jQuery。 – 2013-02-13 01:27:40

相關問題