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() 它是空白的,图像链接仍然会给我一个整数。我很困惑!

4

2 回答 2

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
    }
})
于 2013-02-12T19:57:15.530 回答
-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;
}

}

于 2013-02-12T19:59:13.470 回答