簡體   English   中英

如何使用 jquery 縮短我的代碼?

[英]How can i do shorten my code with jquery?

 <div class="logo-contentBlock"> 
   <a href="#logo-first-content" class="content-page-scroll-1">BLOG</a>
 </div>

 <div id="#logo-first-content"></div>




    $(".content-page-scroll-1").click(function() {
        $('html, body').animate({
            scrollTop: $('#content-first-content').offset().top - 60
        },5000);
    });
    $(".content-page-scroll-2").click(function() {
        $('html, body').animate({
            scrollTop: $('#content-second-content').offset().top - 60
        }, 5000);
    });
    $(".content-page-scroll-3").click(function() {
        $('html, body').animate({
            scrollTop: $('#logo-thirt-content').offset().top - 60
        }, 5000);
    });

我有大約 9 個這樣的代碼。 我怎樣才能縮短它們? 單擊按鈕,它們都 go 到不同的 div。

這將是我針對上述問題的有針對性的解決方案。

<div class="content-page-scroll" data-id="content-first-content"></div>
<div class="content-page-scroll" data-id="content-second-content"></div>
<div class="content-page-scroll" data-id="content-third-content"></div>
            .
            .
            .
<div class="content-page-scroll" data-id="content-n-content"></div>

這里是點擊事件的 JS 代碼。

$(".content-page-scroll").click(function () {
$thisDataId = $(this).data('id');
$('html, body').animate({
      scrollTop: $(`#${$thisDataId}`).offset().top - 60
     }, 5000);
});

這樣,你就用一個JS點擊事件來總結這個問題。 希望它可以幫助您解決此問題。

我會像這樣創建一個 function :

function createScrollClick(elem, location) {
    $(elem).click(function() {
        $('html, body').animate({
            scrollTop: $(location).offset().top - 60
        },5000);
    });
}

然后調用它九次,你需要為每次要設置的點擊調用它:

createScrollClick('.content-page-scroll-1', '#content-first-content'')等。

...或者您可以將所有這些值放入一個數組或 object 並循環調用 function 的這些值。

在 php 中:

<script>
<?php
for ($x=1; $x<9; $x++){
echo '$(".content-page-scroll-'.$x.'").click(function() {
        $(\'html, body\').animate({
            scrollTop: $(\'#content-'.$x.'-content\').offset().top - 60
        },5000);
    });';
}
?>
</script>

暫無
暫無

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

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