...

JQuery next () for elements not next to each other

I have a bit of terrible code that I have to deal with

...
<div class="container">
   ...
    <tr>
    <td width="100" height="50">
         <a class="swaps"><img src="http://www.blah.jpg" alt="Some Title" id="1"></a></span></td>
    </tr>
   <tr>
    <td width="100" height="50">
        <a class="swaps"><img src="http://www.blah2.jpg" alt="Another title" id="2"></a></span></td>
    </tr>
</div>

If i use

var thisone = $("#container .swaps:first")

to select the first one (with id 1), why am I having trouble choosing

thisone.next()?

+3
source share
8 answers

Is HTML real? I do not see any element with the identifier "container", and you do

$("#container .swaps:first")

Also, if this is real HTML, you should fix it a bit (close the img tag and add an opening tag for the range before </TD>)

Assuming your HTML is OK, this should work for your script.

var thisone = $("#container .swaps:first");
thisone.children();

IMG is not an anchor brother, is a child.

+4
source

, Jquery docs :

. : eq (0). : (1). : first-child : .

.children() $(selector).children();

+1

next() ... .swaps... try $( "# container.swaps" )

+1

jQuery next() , DOM ( jQuery) .

$("#container .swaps:first")

, next() undefined, . , , , next().

jQuery . .

// Naive way
var items = $("#container .swaps");
var i = 0;
items[i++] // first <a>
items[i++] // second <a>

, , Iterator - , jQuery, - . :

// Iterator function
function Iterator(list) {
    var results = list;
    var i = 0;

    this.next = function() {
        return results[i++];
    };

    return this;
}

// Usage
var iterator = Iterator($("#container .swaps"));
iterator.next() // first <a>
iterator.next() // second <a>

, jQuery:

// jQuery plugin
$.fn.iterator = function() {
    var i = 0;

    this.next = function() {
        return this[i++];
    };

    return this;
};

// Usage
var iterator = $("#container .swaps").iterator();
iterator.next() // first <a>
iterator.next() // second <a>

Javascript 1.7 , - ​​ Firefox .

+1

:first, , "". :first-child.

0

thisone.next() , ( ). , thisone, img, thisone.children("img").

0

var thisone = $("div.container a.swaps:first");
var img = thisone.children(img);

. .

0

-, , , .

, , , , .swaps :

$('#container .swaps').each(function(){
 var swapImg = $(this).find('img');
 // do something else
})
0
source

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


All Articles