使用jQuery查找元素的父元素

Çağ*_*daş 0 jquery

可能重复:
检测最近或父div

我需要一些关于使用jquery查找元素的帮助.作为主题提示,我需要找到给定元素的容器.我已经有了类似的代码;

$('.cancel_button').bind "click", (event) ->
    element = $(this.parentElement)
    ...
    ...
Run Code Online (Sandbox Code Playgroud)

但对我来说这似乎很难看.取消button是一个section元素.我想知道是否有可能做类似的事情

$(this).containerElement('section')
Run Code Online (Sandbox Code Playgroud)

Ama*_*dan 6

您可能正在寻找parent或closest:

$(this).parent()

// or

$(this).closest('section')
Run Code Online (Sandbox Code Playgroud)

您甚至可能希望将它们组合在一起,因为如果它匹配closest将返回当前元素.所以如果你有一个div在一个section范围内div:

<div id="outer">
    <section>
        <div id="inner">....</div>
    </section>
</div>
Run Code Online (Sandbox Code Playgroud)

......而且你想outer在事件发生时得到inner它,它是:

$(this).parent().closest('div');
Run Code Online (Sandbox Code Playgroud)

但是当您开始使用的元素与选择器不匹配时,您不需要它.

  • +1最有可能"最接近". (2认同)