使用相同的jQuery函数来控制同一页面上的多个实例

时间:2015-01-16 15:18:27

标签: jquery function

我在同一页面上有两个不同的div需要以完全相同的方式滚动内容。我当前的代码运行良好,但可能有更好的方法来实现这一点。我只是不知道如何告诉jQuery在#container-1中使用#move-1而在同一个函数中使用#move-2#container-2。谁能告诉我怎么做?

HTML

<div id="container-1" class="container">
    <div class="item item-1">container 1 - item 1</div>
    <div class="item item-2">container 1 - item 2</div>
    <div class="item item-3">container 1 - item 3</div>
</div>
    <button id="move-1">Move item in container 1</button>
<div id="container-2" class="container">
    <div class="item item-1">container 2 - item 1</div>
    <div class="item item-2">container 2 - item 2</div>
    <div class="item item-3">container 2 - item 3</div>
</div>
    <button id="move-2">Move item in container 2</button>

的jQuery

$( "#move-1" ).click(function() 
    {
        $( "#container-1 .item" ).animate({ "top": "-=200px" }, "slow" );
    });

$( "#move-2" ).click(function() 
    {
        $( "#container-2 .item" ).animate({ "top": "-=200px" }, "slow" );
    });

CSS

body {
    background: #fff;
}

.container {
    position: relative;
    background-color: #f5f5f5;
    width: 240px;
    height: 200px;
    overflow: hidden;
    font-family: arial, sans;
    font-weight: bold;
    text-align: center;
}

.item {
    position: absolute;
    width: 190px;
    height: 90px;
    color: #000;
    overflow: auto;
}

.item-1 {
    top: 0px;
}

.item-2 {
    top: 200px;
}

.item-3 {
    top: 400px;
}

button {
    margin-bottom: 20px;
}

JSFIDDLE

2 个答案:

答案 0 :(得分:0)

您可以使用所点击元素的ID并获取数字

$('[id^="move-"]').on('click', function()  {
    var id = this.id.split('-').pop();
    $('#container-' + id + ' .item').animate({ "top": "-=200px" }, "slow" );
});

FIDDLE

答案 1 :(得分:0)

非常简单,如果你的HTML在整个过程中都是相同的,你可以使用prev()获取前一个元素,然后在其中找到子项:

$('button').click(function() {
   $(this).prev().find('.item').animate({ "top": "-=200px" }, "slow" );
});

FIDDLE