【问题标题】:Target next siblings child to get outerheight瞄准下一个兄弟姐妹的孩子以获得外高
【发布时间】:2018-08-10 21:16:20
【问题描述】:

我想在下面的示例中获取类 .child 的高度值,然后使用警报显示该值以进行故障排除。

我有两个元素 .first.second 是兄弟姐妹,.second 元素有一个名为 .child 的子元素

HTML:

<div class="parent">

  <div class="first">Click Me</div>

  <div class="second">
    <div class="child"></div>
  </div>

</div>

CSS:

.first {
   width: 60px;
   padding: 8px;
   background: blue;
}

.child {
   height: 1234px;
}

jQuery:

$(".first").click(function() {

  var childHeight = $(this).next(".second > .child").outerHeight();

  alert(childHeight);

});

问题似乎在于针对孩子,如果我从我的 var 中删除 &gt; .child,它会返回 .second 的高度

这是一个 JS fiddle,代码相同:https://jsfiddle.net/CultureInspired/6dxLp86b/

【问题讨论】:

  • 我也试过用 find 代替 next,以及 nextAll 或 nextUntil

标签: javascript jquery parent-child next siblings


【解决方案1】:

您应该使用.next(".second").find(".child") 来正确获取子元素。

这将获取下一个元素,然后会在其中找到.child 元素。

$(".first").click(function() {

  var childHeight = $(this).next(".second").find(".child").outerHeight();
  alert(childHeight);

});
.first {
  width: 60px;
  padding: 8px;
  background: blue;
}

.child {
  height: 1234px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">

  <div class="first">Click Me</div>

  <div class="second">
    <div class="child"></div>
  </div>

</div>

【讨论】:

  • 效果很好,我可以发誓我昨晚尝试过这种方法不止一次,感谢您的帮助。
  • @SamAssoum 很高兴它有帮助!请务必将答案标记为正确:)
  • 我要等 8 分钟 :)
  • @SamAssoum 确定
猜你喜欢
  • 2018-03-16
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多