javascript - 目标下一个 sibling 的 child 获得外部高度

标签 javascript jquery jquery-selectors parent-child siblings

我想获取下例中 .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);

});

问题似乎在于针对子项,如果我从我的变量中删除 > .child ,它会返回 .second 的高度

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

最佳答案

您应该使用 .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>

关于javascript - 目标下一个 sibling 的 child 获得外部高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072818/

相关文章:

javascript - 如何用取消停止可排序事件

jQuery:以数组形式返回复选框的值?

html - Jquery 下一个按钮不适用于图片库

javascript - jQuery 选择器作为属性存储在命名空间中

JavaScript 使用 FormData 和 jQuery 的 ajax 上传文件在 iOS 上没有选择文件时返回错误 500

javascript - 如何从 AJAX 包装函数返回

javascript - 暂时性错误,使用 if 子句跳过空白单元格

javascript - 仅使用 Angular 形式可以吗?

javascript - 下拉列表自动填充到页面上的文本(非输入字段)

javascript - PHP中显示AJAX函数返回的多个值时出错