带有过滤器的 jQuery 单属性、多值选择器 [英] jQuery Single Attribute, Multiple Values Selector with filter
本文介绍了带有过滤器的 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://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>
这篇关于带有过滤器的 jQuery 单属性、多值选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文