Using jquery next to finding a "nested" brother

This may be a simple solution, but I can't figure it out.

I have a bunch of images sitting like this:

<div class='image-bar'>
    <span>
      <img class='my-image' src='blah1' id='1'>
    </span>
    <span>
      <img class='my-image' src='blah2' id='2'>
    </span>
    <span>
      <img class='my-image' src='blah3' id='3'>
    </span>
</div>

Given the image id, I need to find the next and previous image using jQuery.

Using 2 as an example, I tried the following to get the following image:

$('.image-bar').find('.my-image[id="2"]').next();

I think that until the "attribute equals" selector is selected, but since the image with id 3 is not even marriage, the following () does not work. How can I handle this? Any pointers are welcome!

+4
source share
3 answers

, , .

var next = $('.image-bar').find('.my-image[id=2]').parent().next().find('img');
var prev = $('.image-bar').find('.my-image[id=2]').parent().prev().find('img');

, , :

var elementId = "2";
var next = $('.image-bar').find('.my-image[id=' + elementId + ']').parent().next().find('img');
var prev = $('.image-bar').find('.my-image[id=' + elementId + ']').parent().prev().find('img');
+2

id ,

var imgArray = $(".my-image"); // this will have an array with all images

id = 2

var id = 2;
imageArray[id-1]; // returns image with id 2

imageArray[id];

imageArray[id-2];

NB: , .

var imgArray = $(".my-image"); // this will have an array with all images

console.log( getImage(2/* image id */, "next"));

function getImage(id, pos) {
   var returnImage; 

   if(pos === "next") {
       returnImage = imgArray[id] ? imgArray[id] : "";  
   }
   else if(pos === "prev") {
        returnImage = imgArray[id - 2 ] ? imgArray[id - 2] : "";    
   }
   else {
       returnImage = imgArray[id-1] ? imgArray[id-1] : "";      
   }
   return returnImage;
}
0

Try using .filter(), .index(),.slice()

var imgs = $(".image-bar img");

var curr = imgs.filter("#2");

var i = curr.index(imgs.selector);

var prev = imgs.slice(i - 1, i);

var next = imgs.slice(i + 1, i + 2);

console.log("curr:"+curr[0].id
           , "curr index:" + i
           , "prev:" + prev[0].id
           , "next:" + next[0].id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class='image-bar'>
    <span>
      <img class='my-image' src='blah1' id='1'>
    </span>
    <span>
      <img class='my-image' src='blah2' id='2'>
    </span>
    <span>
      <img class='my-image' src='blah3' id='3'>
    </span>
</div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1616781/


All Articles