如何为给定按钮选择相应的div?

时间:2016-12-10 12:20:53

标签: jquery

这里我有五个按钮和五个div。如果我单击第一个按钮,那么一些数据应仅填入第一个div,而不是其他数据。连续按钮也是如此。我在jQuery中这样做。

$(document).ready(function () {
    $(".btn").each(function () {
        // code  here to put some data in relative div
    });
});
<button type="button" class="btn">Button 1</button>
<button type="button" class="btn">Button 2</button>
<button type="button" class="btn">Button 3</button>
<button type="button" class="btn">Button 4</button>
<button type="button" class="btn">Button 5</button>

<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>

1 个答案:

答案 0 :(得分:2)

首先请注意,如果您希望在点击按钮时发生这种情况,则应使用click()方法,而不是each()

要使其工作,您可以使用index()方法查找所点击按钮的索引,并使用eq()方法将该索引与相关.myDiv相关联。试试这个:

$(".btn").click(function() {
  var index = $(this).index('button');
  $('.myDiv').eq(index).text('clicked button ' + (index + 1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn">Button 1</button>
<button type="button" class="btn">Button 2</button>
<button type="button" class="btn">Button 3</button>
<button type="button" class="btn">Button 4</button>
<button type="button" class="btn">Button 5</button>

<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>