簡體   English   中英

jQuery / Java代碼重復

[英]jQuery/Javascript code repetition

我試圖在我的程序中使用scrollTop函數,但是發現我正在寫很多重復的代碼。

這是一個例子:

<div id="table_contents >
    <ul>
        <li id="one"> title One </li>
        <li id="two"> title Two </li>
    </ul>
</div>


<div id="content">
    <p id="target_one"> I am content one </p>

    <p id="target_two"> I am content two </p>
</div>

如果我要單擊“標題一”,我想滾動到“我是內容一”,同樣,標題二和內容二也是如此。

這很容易用jQuery / JS完成

$("#one").click(function() {
        $('html, body').animate({
            scrollTop: $("#target_one").offset().top -20
        }, 800);
    });

但是例如說我的目錄中有15個元素,我想讓每個可單擊的滾動到其內容。 為此,我將對每個元素重復以上代碼15次。

有沒有比這更好的方法了?

只需將腳本更改為:

方法1

$("#table_contents").on("click","li",function() {
        $('html, body').animate({
            scrollTop: $("#target_"+$(this).prop('id')).offset().top -20
        }, 800);
    });

在此方法中,被單擊元素的id將附加到“ target_”,以找到“目標ID”。 該方法甚至適用於動態添加的li元素。


方法2不使用ID [但順序相同]:

$("#table_contents").on("click","li",function() {
        $('html, body').animate({
            scrollTop: $("#content p").eq($(this).index()).offset().top -20
        }, 800);
    });

在這種方法中,元素li的索引映射到p元素的索引以定位滾動位置。

並做了!!

http://jsfiddle.net/bmL0o9ez/

http://jsfiddle.net/bmL0o9ez/2/

現場演示

$("#table_contents ul li").click(function () {

    var theIdAttr = $(this).attr("id");

    $("html, body").animate({
        scrollTop: $("#target_" + theIdAttr).offset().top -20
    });

});

您可以將更通用的選擇器用於事物的類型排序,其中每個元素都需要相同的行為。

$("#table_contents li").click(function() {
        var liElement = $(this);
        $('html, body').animate({
            scrollTop: $("#target_" + liElement.attr('id')).offset().top -20
        }, 800);
    });

您可以根據li的ID動態構建段落的ID。

的HTML

    標題一標題二

<div id="content">
    <p id="target_one"> I am content one </p>

    <p id="target_two"> I am content two </p>
</div>

Javascript:

$("#table_contents li").click(function() {
    $('html, body').animate({
        scrollTop: $('#target_' + $(this).attr('id')).offset().top -20
    }, 800);
 });

使它通用,例如:

$("#table_contents ul li").click(function() {
        $('html, body').animate({
            scrollTop: $('#target_'+ $(this).attr("id")).getId.offset().top -20
        }, 800);
    });

如果您按順序排列內容,那么甚至可以使用通用名稱,例如:

$("#table_contents ul li").click(function() {
        var index = $(this).index();
        $('html, body').animate({
            scrollTop: $('#content:nth-child('+index+')').getId.offset().top -20
        }, 800);
    });

未經測試,但是應該可以給您一個想法

喝彩

這是一個完全不依賴使用ID的解決方案,而是使用jQuery的index()函數:

$("#table_contents li").click(function () {
    $('html, body').animate({
        scrollTop: $("p").eq($(this).index()).offset().top - 20
    }, 800);
});

jsFiddle示例

我做

$("#content p").each(function() {
    var heights = [];
    heights.push($(this).offset().top);
});

然后做

heights[your_target_as_index];

做完了嗎

暫無
暫無

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

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