我需要根据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()它是空白的。我很困惑!
答案 0 :(得分: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
}
})
答案 1 :(得分:-4)
您应该使用HTTP HEAD来查看内容上下文。
这是一个可以从中剪切位的示例,它用作检查器以查看是否存在URL:
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;
}
}