如何将"this"与情商或x孩子相结合



我需要定位父 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>

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

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

$("#one").click(function() {
  var q = $(this).children().eq(1).attr('class');
  console.log(q); 
})
<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>


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

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

$("#one").click(function() {
  var q = $(this).children(':nth-child(2)').attr('class');
  console.log(q); 
})
<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>

您需要找到第二个Div

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

最新更新