简体   繁体   中英

jQuery: Accessing an element from an object with multiple instances of a class

I am trying to do a simple tab navigation.

I was thinking I could put all buttons in an object, do the same with the content divs, get index of clicked button and access the content div using that index number to make the respective content show up. What am I doing wrong?

HTML:

<div class="row">
    <a class="btn" href="#">One</a>
    <a class="btn" href="#">Two</a>
    <a class="btn" href="#">Three</a>
    <a class="btn" href="#">Four</a>
</div>
<div class="row">
    <div class="content">Content 1</div>
    <div class="content">Content 2</div>
    <div class="content">Content 3</div>
    <div class="content">Content 4</div>
</div>

jQuery:

$(document).ready(function(){
    var $btn = $('.btn');
    var $content = $('.content');

    $btn.each(function(){
        $(this).on('click', function(){
            $content.hide();
            var i = $btn.index(this);
            $content[i].show(); //This does not work
        });
    });
});

jsFiddle: http://jsfiddle.net/pcr0zuuo/

Thanks in advance!

Your issue is that show() is a jQuery function. However doing the offset [i] off of a jQuery object will return you the raw dom element. You should use eq(index) instead to get the jQuery object back to operate on.

Essentially the issue is that you tried using a jQuery function on a normal DOM node. You can fix it in two ways:

$( $content[i] ).show()

or

$content.eq(i).show()

Both should properly wrap the element and show it as you'd expect. ( http://jsfiddle.net/pcr0zuuo/1/ )

jQuery's collections aren't arrays of jQuery objects, the array reference is to the DOM object. The collection of $content can't be referenced with [] to run jQuery functions. So change to:

$content.eq(i).show();

and it works in your jsFiddle. (Thanks to Taplar for the hint)

You logic is correct. You can target the index of the class .btn and show the corresponding divs.

If you want to use jquery, use index() function to find index and eq to target the index.

$('.btn').click(function()
{
    $('.content').eq($(this).index()).show();
});

http://jsfiddle.net/eqntjb01/

Alternately, you can implement it via javascript ( the way you were trying to do in the example )

$('.btn').click(function()
{
  $('.content')[$(this).index()].style.display = "block";
});

http://jsfiddle.net/eqntjb01/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM