Domanda

Looking for a way to accomplish populating a div with jQuery, traversing.. which I'm no good at.

My code has a series of 6 boxes and then a content box.. another 6 boxes and a content box like so:

<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='content'></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='content'></div>

What I am looking for is when somebody clicks on the image - it populates the next .content div only.

Thanks in advance.

=== For Hugo.. The closest I got, which obviously populates all the content boxes is:

$(".box img").click(function(){
                $(this).parent().parent().find(".content").html("X");
            });
È stato utile?

Soluzione

$('.box img').click(function(){
   $(this).parent().nextAll('.content').first().text('...');
})

Altri suggerimenti

You need to use the appropriate traversal functions for this. The "best" version depends on your markup and the relative stability of its various pieces, but for now let's just work with the HTML you give.

Starting from any <img>, you want to move up to its parent .box and then look for the next .content. Translating to jQuery:

$(this).parent().nextAll(".content").first()
$('img').click(function() {
  var $nextdiv = $(this).parent().nextUntil('.content').addBack().last().next();
  // do something with it
});

http://jsfiddle.net/mblase75/gRKfa/

http://api.jquery.com/nextUntil

(.nextAll().first() is rather less complicated, though.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top