我想用 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
按钮时,我希望它找到 ID 为 second-module
的 div
。
当我点击 Trigger 2
时,我希望它找到 ID 为 first-module
而 notdiv > second-module
,因为它比 Trigger 2
按钮嵌套得更深。
是否有用于此的 jQuery 函数?
最佳答案
尝试使用 .closest()
$('.trigger').click(function() {
$(this).closest('.module');
});
关于javascript - 通过向后遍历 DOM 获取最近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122746/