jQuery单属性,带过滤器的多值选择器

时间:2019-01-08 23:41:57

标签: jquery selector

//Images
var boxlinks = $('a[href]').filter('[href$=".png"], [href$=".gif"], [href$=".jpg"], [href$=".jpeg"]');

在jQuery中,有没有一种更有效的方法可以使用过滤器选择单个属性的多个值,在这里我试图选择仅将图像用作href的链接。

1 个答案:

答案 0 :(得分:1)

这里是使用正则表达式和类的示例。正则表达式小写href,因此它不敏感。

var boxlinks = $('a[href]').filter(function(){
      // regex checks for a literal period, followed by one of the extensions, and then
      // the end of the line
  return /[.](png|gif|jpg|jpeg)$/.test(this.href.toLowerCase());
});

console.log(boxlinks.get());
console.log($('a.image').get());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://stackoverflow.com/something/something/thing.txt"></a>
<a href="https://stackoverflow.com/something/something/thing.png" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.gif" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.jpg" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.jpeg" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.PNG" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.GIF" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.JPG" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.JPEG" class="image"></a>