【问题标题】:Find if link targets image with javascript/jquery查找链接是否使用 javascript/jquery 定位图像
【发布时间】:2012-01-12 00:23:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: jquery regex


    【解决方案1】:

    你几乎拥有它!!!

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

    【讨论】:

      【解决方案2】:

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

      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");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-24
        • 2015-09-26
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多