jQuery 如何根据数据属性的值过滤对象数组?

jQuery How to filter an object array based on the value of a data-attribute?

如果我正在处理返回的图像数组,我该如何过滤掉那些包含特定数据属性值的图像?

例如...

let $exampleImages = $("#example img");

现在每个示例图像 returns 类似于

$exampleImages[5] => <img ... data-targetattribute="12345" ... >

如何才能只过滤掉那些包含 data-targetattribute="12345" 的图像?

我以为下面的方法会起作用,但它不起作用...

$exampleImages.filter('[data-targetattribute="12345"]');

有什么想法吗?过滤方法或对象集合有什么我没有正确理解的地方吗?

我也没有嫁给 jQuery 所以如果这更适合原始 Javascript 方法,我洗耳恭听!

谢谢!

要从 jQuery 对象中过滤具有给定数据属性值的项目,.filter([selector]) 方法将实现您想要的。

这里有一些示例代码演示了这一点:

var divs = $('div');

divs = divs.filter('[data-targetattribute="12345"]')

divs.css('background-color', 'red');

JSFiddle

请注意 .filter returns 一个新对象。您的代码遇到的问题可能是您试图引用未更改的初始变量。