jQuery/Javascript代码重复

jea*_*ean 1 html javascript jquery

我正在尝试将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>
Run Code Online (Sandbox Code Playgroud)

如果我点击'标题一'我想滚动到'我满足一个'同样为标题二和内容二.

这很容易与jQuery/JS一起使用

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

但是比如说我的目录中有15个元素,我想让每个可点击的内容都滚动到它的内容.为此,我必须为每个元素重复上述代码15次.

还有比这更好的方法吗?

Him*_*agi 5

只需将脚本更改为:

方法1

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

在此方法中,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);
    });
Run Code Online (Sandbox Code Playgroud)

在此方法中,元素li的索引映射到元素的索引p以定位滚动位置.

并做了!!

http://jsfiddle.net/bmL0o9ez/

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