开发者

jQuery element index in array

开发者 https://www.devze.com 2022-12-10 17:11 出处:网络
I have several images loaded into the DOM via jQuery. Each image has \'display: none\' aside from one which is \'display: block\'. It\'s this image which I need to find the index of once selecting the

I have several images loaded into the DOM via jQuery. Each image has 'display: none' aside from one which is 'display: block'. It's this image which I need to find the index of once selecting the img array from the DOM.

The trouble is, img[style="display: block"] doesn't seem to be working as 'display' isn't the only style set on the elemen开发者_JAVA技巧t. There's top, left, etc...

How can I find the index of the image with display:block from a selection of images with display:none?

Current code I'm using:

slideshowStart = jQuery('.gallery .slideshow img[style="display: block"]').index(this);


You can use the :visible selector for this:

var slideshowStart = $(".gallery .slideshow img:visible").index(this);


You almost have it there. According to the documentation, you want to change the img portion of your query to the following:

img[style*="display: block"]


you should consider adding a class for those images and add the CSS:

.isBlock {
  display: block
}

.isNone {
  dispay: none
}

Then use:

jQuery('.gallery .slideshow img.isBlock');

You can then use .addClass and .removeClass to change the image that has the display: Block. This might give you some more lines of code but it should improve performance on browsers that support getElementByClassName() function and make the code more human readable. Check my comment selector performance on this answer. Looking for attributes is very expensive, looking for class name is a lot faster (and if the browser implements that function it should be as fast as looking for ID).

0

精彩评论

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

关注公众号