如何将“this”与eq或x-child结合起来

时间:2017-09-26 11:25:45

标签: javascript jquery

我需要定位父foo的第二个孩子。我怎么能这样做?

$("#one").click(function() {
  // How to get "me" if I do not know the classname?
  // I need to target that second div (I know that it's second).
  var q = $(this).eq(1).attr('class');
  console.log(q); // undefined

  // Aim?
  // I need that element or classname
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
  <div>one</div>
  <div class="me"></div>
</div>

2 个答案:

答案 0 :(得分:3)

您需要先让孩子,然后应用eq()方法。

var q = $(this).children().eq(1).attr('class');

&#13;
&#13;
$("#one").click(function() {

  var q = $(this).children().eq(1).attr('class');
  console.log(q); 
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
1
 <div></div>
 <div class="me"></div>
</div>
&#13;
&#13;
&#13;

或使用:nth-child选择器作为children()方法的参数。

var q = $(this).children(':nth-child(2)').attr('class');

&#13;
&#13;
$("#one").click(function() {

  var q = $(this).children(':nth-child(2)').attr('class');
  console.log(q); 
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
1
 <div></div>
 <div class="me"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你需要找到第二个div

$(this).find('div:eq(1)').attr('class')