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

问题描述:

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

是否有更有效的方法在 jQuery 中使用过滤器选择单个属性的多个值,这里我尝试仅选择带有图像作为 href 的链接.

Is there a more efficient way to select multiple values of a single attribute with a filter in jQuery, here I am trying to select links only with an image as an href.

这是一个使用正则表达式和类的示例.正则表达式将 href 小写,因此不敏感.

Here is an example that uses a regex and a class. The regex lowercases the href so it's insensitive.

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://*.com/something/something/thing.txt"></a>
<a href="https://*.com/something/something/thing.png" class="image"></a>
<a href="https://*.com/something/something/thing.gif" class="image"></a>
<a href="https://*.com/something/something/thing.jpg" class="image"></a>
<a href="https://*.com/something/something/thing.jpeg" class="image"></a>
<a href="https://*.com/something/something/thing.PNG" class="image"></a>
<a href="https://*.com/something/something/thing.GIF" class="image"></a>
<a href="https://*.com/something/something/thing.JPG" class="image"></a>
<a href="https://*.com/something/something/thing.JPEG" class="image"></a>