开发者

Is there a way to select on a value attached by .data()?

开发者 https://www.devze.com 2023-01-30 18:49 出处:网络
Background: I\'m performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

Background: I'm performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

So my question i开发者_运维百科s this: I'm setting some data on each image that gives the image's index, the index of the next image, and the index of the previous image, like so:

$(this).data('index', i).data('prev', i - 1).data('next', i + 1);

Later on, I'd like to be able to select an image based on its index. I've tried the following, but it doesn't seem to work:

$('[data-index=' + index + ']');

Is there a way to select an element based on a piece of data attached with .data()?


You can use .filter(), like this:

$('*').filter(function() { return $.data(this, 'index') == index; })

However, * is very expensive, as it runs this filter on all elements, please use a more specific selector to start with.


Slightly alternative approach:

Assuming the images are in a series in the HTML, why not just do something like this?

$('#images img').eq(index)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号