4

我想用 jQuery 获得一个 DOM 元素,但我只想在 DOM 中向后看。

所以假设我有以下 HTML 结构:

<div id="content">
    <div id="first-module" class="module">
        <h3>Some Module</h3>
        <p>Lorem ipsum... </p>

        <div id="some-other-content">
            <div id="second-module" class="module">
                <h3>Some other module</h3>
                <p>Dolor sit amet...</p>
                <button class="trigger">Trigger 1</button>
            </div>
        </div>

        <button class="trigger">Trigger 2</button>
        <div id="third-module" class="module">
            <h3>Another module</h3>
        </div>
    <div>
</div>

$('.trigger').click(function() {
    // Traverse DOM to find closest .module class
});

因此,当我单击Trigger 1按钮时,我希望它找到div带有 ID的按钮second-module

当我单击时,Trigger 2我希望它找到div带有 IDfirst-module不是 second-module,因为它的嵌套比Trigger 2按钮更深。

有没有一个jQuery函数呢?

4

3 回答 3

4

尝试使用.closest()

$('.trigger').click(function() {
    $(this).closest('.module');
});
于 2013-04-20T16:44:54.863 回答
4

是的,我们确实有.closest()

$('.trigger').click(function() {
    // Traverse DOM to find closest .module class
    var id = $(this).closest('.module').attr('id');
    alert(id);
});

在这里演示

于 2013-04-20T16:47:09.233 回答
1

另一种访问它的方法是使用 父选择器

$('.trigger').click(function() {
   console.log($(this).parent('.module').attr('id'));
    // Traverse DOM to find closest .module class
});
于 2013-04-20T16:47:39.213 回答