簡體   English   中英

使用jQuery選擇:last-child

[英]selecting :last-child using jquery

我有一個輪播,菜單區域中的每個錨點都鏈接到選定的幻燈片,並且當菜單中的錨點被選擇時,它會收到一個.active類。 例如:鏈接1 =幻燈片1。當輪播到達最后一個滑塊時,我嘗試添加一個停止按鈕,而不是下一個。

<nav class="meniu">
    <a href="#">Slide 1</a>
    <a href="#">Slide 2</a>
    <a href="#">Slide 3</a>
</nav>
<div id="slider">
    <ul>
        <li>Slide 1</li>
        <li>Slide 2</li>
        <li>Slide 3</li>
    </ul>
</div>

這是我嘗試添加的腳本

if ($('.meniu a:last-child').hasClass('active')){
    //change button arrow to stop sign
}

這是小提琴-http: //jsfiddle.net/G7P46/1/

好的,這是您的問題。

僅使用來回按鈕時,您將獲得具有“活動”類的元素,然后刪除該類,然后將其添加到下一個同級中。 這是問題所在。 如果僅使用按鈕,則實際上不會將錨設置為活動狀態。 因此,查找活動的jquery選擇器將返回0。由於沒有“ next”,因此它無法檢查最后一個元素是否處於活動狀態。

現在,如果您單擊鏈接,然后使用按鈕,那么它將起作用,因為至少一個錨點已設置為“活動”。

這是一個工作的小提琴。

http://jsfiddle.net/G7P46/2/

我更新了gonext函數

function goNext() {
    if (decount != counter) {
        $('#slider ul').animate({
            left: '-=' + $('#slider').width()
        }, 800, 'swing', function () {

        });
        if ($('.active').length == 0) {
            $('.meniu a:first-child').addClass('active');
        }
        $('.active').removeClass('active').next().addClass('active');
        if ($('.meniu a:last-child').hasClass('active')) {
            console.log('change button');
        }

        decount++;
        window.location.hash = decount;

    }
}

注意,我添加了一個檢查以查看是否有設置為活動的錨。 如果沒有,我將第一個孩子設置為活動狀態。 我還添加了更改按鈕if語句。 現在受到打擊。

另外,我更新了點擊事件

$('.meniu a').on('click', function () {
    var goTo = this.id * -$('#slider').width() + $('#slider').width();
    $('#slider ul').animate({
        left: goTo
    }, 800, 'swing', function () {});
    $('.active').removeClass('active');
    $(this).addClass('active');
    decount = this.id;
    window.location.hash = this.id;
    if ($('.meniu a:last-child').hasClass('active')) {
        console.log('change button');
    }


});

現在,它檢查那里的最后一個錨點。

編輯:我再次更新小提琴以具有實際的按鈕更改功能

http://jsfiddle.net/G7P46/3/

嘗試這個 :

if ($('.meniu a:last').hasClass('active')){
    //change button arrow to stop sign
}

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM