2013-02-12 46 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