如何使用javascript或jquery检查href路径是否包含图像或其他链接

How can I check if the href path contain image or someother link using javascript or jquery?

本文关键字:包含 是否 图像 路径 其他 链接 href 何使用 javascript jquery 检查      更新时间:2023-09-26

任何人都知道告诉我这样做的建议。如何检查锚点href属性是否包含图像路径或其他路径。

例如:

    <a href="image.jpg"><img src="image.jpg"/></a>
    <a href="http://google.com"><img src="image.jpg"/></a>

参见上面的示例显示href属性包含不同的路径,第一个是图像,第二个是其他网站链接。我仍然对此感到困惑,如何使用jquery或javascript检查href路径是否包含图像路径或其他路径。

任何建议都很好。

例如(如果需要,您可能需要包括其他图片格式):

$("a").each(function(i, el) {
  var href_value = el.href;
  if (/'.(jpg|png|gif)$/.test(href_value)) {
     console.log(href_value + " is a pic");
  } else {
     console.log(href_value + " is not a pic");
  }
});
Jquery:
$(document).ready( function() {
  var checkhref = $('a').attr('href');
  var image_check = checkhref.substr(checkhref.length - 4)
  http_tag = "http";
  image = [".png",".jpg",".bmp"]
  if(checkhref.search("http_tag") >= 0){
    alert('Http!');
    //Do something
  }
  if($.inArray(image_check, image) > -1){
    alert('Image!');
    //Do something
  }
});

您可以在没有jQuery 的情况下检查图像是否存在

Fiddle

 var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
    document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
    document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);