jQuery using index()

jQuery using index()

本文关键字:index using jQuery      更新时间:2023-09-26

我很难解释我想要什么,但我会试一试。

好的,左边是html。

<div></div>
<div></div>
<div></div>
<div></div>

以下是右侧输出的内容。

<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div> 

我试着让它变得这样,当你点击左边的第一个div时,右边的第一个divs就会出现,当你单击左边的第二个divs时,右边第二个div就会出现,而右边的所有其他div都会再次隐藏,以此类推。我知道你可以用jQuery中的.index()来做,但我想知道我是否能得到一些关于如何做的帮助。谢谢!

类似的东西?

标记

<div class="left">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>
<div class="right">
    <div class="block">Result 1</div>
    <div class="block">Result 2</div>
    <div class="block">Result 3</div>
    <div class="block">Result 4</div>
</div>

JS

$(function(){
   $('.left > div').on('click', function(){
        //Just show the respective block div based on the clicked index and hide its siblings that are visible.
        $('.block').eq($(this).index()).show().siblings('.block:visible').hide();
    });
});

演示

有一点滑动效果

$(function () {
    $('.block').eq(0).show();
    $('.left > div').on('click', function () {
        var elemToShow = $('.block').eq($(this).index()); //Get the element to show
        $('.block:visible').stop().slideUp(1000, function () { // slide up the visible block div
            elemToShow.stop().slideDown(1000); // once the animation finishes shidedown the element to show
        });
    });
});

演示幻灯片效果

演示渐变效果

假设您将把一个left类放在左边的divs:上

var $blocks = $('.block'),
    $left = $('.left');
$('.left').click(function () {
    $blocks.hide().eq( $left.index(this) ).show();
});

小提琴在这儿:http://jsfiddle.net/YddrP/

首先,您必须检测左侧元素上的点击。在回调函数中,您必须找到单击的div的索引,然后找到右侧索引与数字匹配的show()

假设左侧的div在一个类为left的容器中,右侧的div在right:中

$('.left').on('click', 'div', function(){ //bind the click event to the left divs
    $('.right div')                       // select all the divs inside .right
        .hide()                           // hide all the divs
        .eq( $(this).index() )            // select the one that matches the clicked index
        .show();                          // show it
});

这是一个演示。

这是on()的文档。

这是eq()的文档。

是的,您可以尝试.index()和:eq().index()返回元素的数字索引,而:eq()通过数字索引返回元素。

假设左div位于类为'left'的外部div内,右div位于'right'内

$('.left div').click(function () {
    $('.right div').hide();
    var i = $('.left div').index(this);
    $('.right div:eq(' + i + ')').show()
});