开发者

jQuery - Dynamic linking of elements in order..?

I have two different classes ".Content" and ".Link" that i want to.. "match" according to the position/order.

HTML:

<div class="Content"> Content1 </div> <!-- First of Contents-->
<div class="Content"> Content2 </div>
<div class="Content"> Content3 </div>

<div class="Link"> Link1 </div> <!-- First of links -->
<div class="Link"> Link2 </div>
<div class="Link"> Link3 </div>

What im trying to achieve is to somehow always link these in order.

If i clicked the first ".Link" it would let me do something to the first ".Content"

and if i clicked ..lets say the 146th ".Link" it would let me do 开发者_C百科something to the 146th ".Content"

The something that is done to the content what ever it is, it doesnt change. It would always do the same function what ever it would be.

I have no starting point for this, just the idea... How could i achieve this?


Use index and eq. index tells you the position of the element among its siblings, and eq gets an element from a position in a selection.

$('div.Link').click(function() {
    var linkIndex = $(this).index();
    $('div.Content').eq(linkIndex).css({color: 'red'});
});

jsFiddle example


Get the index of the element clicked, use that index to access the Content element.

$('.Link').click(function () {
    var content = $('.Content').eq($(this).index($('.Link')))
}


Try this:

$(function(){
 $(".Link").click(function(){
    var index = $(".Link").index(this);
    var content= $(".Content").eq(index);
     //Do Something with content.
 });
});


My idea: I'd use attribute "position" when generating that HTML and then based on that know with what position I am working on. I think it is faster than traversing DOM to figure out position of the element.

If you do not generate the HTML content, I suggest adding attribute programatically via on document loaded.


If you were to put all your content into a single (aka DOM) object, it is quite possible to manipulate / link these in orders in JAVASCRIPT, using the .nextSibling feature.

Hence... in your case, (link1.nextSibling) will give (link2).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜