JQuery - get(0) undefined

2019-08-08 10:43发布

I have this HTML structure:

<div id="navigation">
    <div id="accordion">
        <!-- 1st header and pane -->
        <img src="horisontalTabsAccordion/images/button1.jpg" />
        <div style="width:200px; display:block"><h3>Apolonija, zubarska ordinacija</h3><p>Nesto pise malo vise malo manje :)</p></div>

        <!-- 2nd header and pane -->
        <img src="horisontalTabsAccordion/images/button2.jpg" />
        <div><h3>Apolonija, zubarska ordinacija</h3><p>Nesto pise malo vise malo manje :)</p></div>

        <!-- 3rd header and pane -->
        <img src="horisontalTabsAccordion/images/button3.jpg" />
        <div><h3>Apolonija, zubarska ordinacija</h3><p>Nesto pise malo vise malo manje :)</p></div>

        <!-- 4th header and pane -->
        <img src="horisontalTabsAccordion/images/button4.jpg" />
        <div><h3>Apolonija, zubarska ordinacija</h3><p>Nesto pise malo vise malo manje :)</p></div>
    </div>
    <div id="buttons">
        <a href="#" class="btn-prev"><div class="previous-icon"></div></a>
        <a href="#" class="btn-next"><div class="next-icon"></div></a>
    </div>
</div>

I'm trying to add buttons for activation next and previous tabs of current tab. Image element that is current have class "current".

The JS that i wrote have this form:

$(document).ready(function(e) {
var currentTab = $('#accordion').find('img.current');

$('.btn-prev').bind('click', function(){
    currentTab.prev('img').get(0).click();
    console.log("Previous");

    return false;
});

 $('.btn-next').bind('click', function(){
    currentTab.next('img').get(0).click();
    console.log("Next");

    return false;
});

});

I have error that says that is get(0) undefined. - TypeError: currentTab.prev("img").get(0) is undefined

2条回答
做个烂人
2楼-- · 2019-08-08 11:06

.prev gets the previous element IF it matches the selector, not the previous element THAT matches the selector.

Try this:

currentTab.prevUntil('img').prev().get(0)

.next() will need the same treatment with .nextUntil

You should also do some checking to prevent errors from pressing previous when you are on the first one.

查看更多
Animai°情兽
3楼-- · 2019-08-08 11:08

You dont need to call get(0) because prev get one or none.

查看更多
登录 后发表回答