簡體   English   中英

跟隨jQuery不起作用。 看一看

[英]Following jQuery isn't working. Take a look

碼:

<div>
    <a href="javascript:void(0)" class="back">Back</a>
    <div class="outer"></div>
    <a href="javascript:void(0)" class="next">Next</a>
</div>
<div>
    <a href="javascript:void(0)" class="back">Back</a>
    <div class="outer"></div>
    <a href="javascript:void(0)" class="next">Next</a>
</div>

jQuery代碼:

$('.next').click(function() {
    $('.next').prev().animate({
        scrollLeft: '+=150'
    }, 200);
});
$('.back').click(function() {
    $('.back').next().animate({
        scrollLeft: '-=150'
    }, 200);
});

錯誤:基本上,我具有與上述相同類的更多代碼,並且我想滾動單擊的代碼。 但是上面編寫的代碼滾動了頁面上的所有“ .outer”。 每組代碼位於不同的div中。 沒有提供“外部”的內部材料,該材料可以滾動。

您需要使用當前元素上下文(即this執行代碼。 還要為父元素的兄弟姐妹設置動畫,以便使用$(this).closest('div')遍歷,然后使用.prev()next()

$(function() {
    $('.next').click(function() {
        $(this).closest('div').prev().animate({
            scrollLeft: '+=150'
        }, 200);
    });
    $('.back').click(function() {
        $(this).closest('div').next().animate({
            scrollLeft: '-=150'
        }, 200);
    });
});

簡單使用$(this)獲取當前對象

$('.next').click(function () {
    $(this).prev().animate({ scrollLeft: '+=150'}, 200);
});

$('.back').click(function () {
    $(this).next().animate({ scrollLeft: '-=150'}, 200);
});

不要忘記將代碼包裝在文檔就緒函數中。

<script>
$(document).ready(function() {
    $('.next').click(function () {
        $(this).prev().animate({ scrollLeft: '+=150'}, 200);
    });
    $('.back').click(function () {
        $(this).next().animate({ scrollLeft: '-=150'}, 200);
    });
});
</script>

同樣使用on方法更適合事件綁定,例如

<script>
$(document).ready(function() {
    $('.next').on('click', function () {
        $(this).prev().animate({ scrollLeft: '+=150'}, 200);
    });
    $('.back').on('click', function () {
        $(this).next().animate({ scrollLeft: '-=150'}, 200);
    });
});
</script>

編輯:

正如@GuruprasadRao所指出的,我假設您已經在使用,但是請確保您使用的是HTML5文檔類型,否則您需要在腳本標簽中添加type =“ text / javascript”。

暫無
暫無

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

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