javascript - 使用jquery查找父级父元素

标签 javascript jquery html angularjs

我的 HTML 如下。我需要的是,当有人单击 span 元素时,我想找到其父元素检查一些条件。我使用了 prev() 方法,但它只给了我近父级(这里是parent2)

<div class="container">
    <div class="contain">
        <div id="parent1">
            <div class="parent2">
                <span> Click here</span>
            </div>
        </div>
    </div>
</div>

var currentComponent = $(event.target).prev();//这里我得到了parent2

我怎样才能找到父元素(在本例中为parent2)。我对 jquery 不太熟悉,因此我们将不胜感激。

最佳答案

您可以尝试.closest .

来自文档:

the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. (...) get the first element that matches the selector by testing the element itself and .

它向上遍历 DOM 中的元素祖先,并返回与作为参数传递的选择器匹配的第一个。因此,在您的示例中,您可以执行类似的操作:

$("span").on("click", function(e) {
  var myParent = $(this).closest(".parent2");
  var parentOfMyParent = $(this).closest(".parent1");
  var contain = $(this).closest(".contain");
  var containerAbove = $(this).closest(".container");
});

关于javascript - 使用jquery查找父级父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756549/

相关文章:

javascript - 文件上传表单被 JavaScript 破坏

javascript - javascript 的内联样式更改在移动浏览器 (chrome/dolphin/android) 上不起作用 : why?

javascript - 响应式 Bootstrap 推送菜单

javascript - 根据 anchor 显示/隐藏内容 - 几乎就在那里

html - form 和 div html 元素的默认 css 参数

html - CSS 菱形/三 Angular 形分隔线/边框

javascript - 为什么 Babylon 将 .manifest 扩展名添加到可加载模型中?

javascript - 我需要 Angular/Ionic 应用程序方面的帮助

asp.net - jquery ajax post 转到 MVC 4 中的错误操作方法

javascript - 输入类型提交错误填充