使用javascript / jquery查找链接目标图像

时间:2011-12-03 03:51:27

标签: jquery regex

我正在尝试编写一个脚本,该脚本将找到目标为jpg,gif或png的所有<a>标记,并为其附加函数。

$('a')
    .filter(function(){
        return this.href.match(/*probably some regex here?*/)
    })
    .bind('mouseover', function(){
        alert('foo');
    })

这应该可行,但我不知道正则表达式会是什么样子。如果有更好的方法,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:7)

你几乎拥有它!!!

$('a[href]').filter(function() {
  return /(jpg|gif|png)$/.test($(this).attr('href'))
}).bind('mouseover', function(){
  alert('foo');
})

答案 1 :(得分:1)

您可能希望使用不区分大小写的正则表达式检查文件名。因为有些文件可能是&#34; .JPEG&#34;而不是&#34; .jpeg&#34;。所以试试这个:

var file = "life/is/short.JPG"

if (/(jpg|jpeg|gif|png)$/i.test(file)) {
    alert("the file is an image");
}
else {
    alert("the file is not an image");
}