遍历 DOM 时遇到问题
我有一些看起来像这样的 HTML,
<dl class="dropdown">
<dt><span>Gender</span><a href="">Go</a></dt>
<dd class="shadow_50">
<ul>
<li><a href="#"><span class="option">male</span><span class="value">1</span></a></li>
<li><a href="#"><span class="option">female</span><span class="value">2</span></a></li>
</ul>
</dd>
</dl>
当单击 GO 链接时, DD
设置为隐藏 我有一些代码可以向下或向上滑动 DD。然而我的问题是,当我在页面中有多个实例时,如果这些实例一键打开页面上的所有DD
,我如何定位最接近点击的DD,
我已经尝试过以下
$(".dropdown dt a").click(function(e) {
$(this).closest("dd").slideToggle(defaults.speed);
e.preventDefault();
});
以及这个,
$(".dropdown dt a").click(function(e) {
$(this).next("dd").slideToggle(defaults.speed);
e.preventDefault();
});
但我还没有成功。
I have some HTML that looks likes this,
<dl class="dropdown">
<dt><span>Gender</span><a href="">Go</a></dt>
<dd class="shadow_50">
<ul>
<li><a href="#"><span class="option">male</span><span class="value">1</span></a></li>
<li><a href="#"><span class="option">female</span><span class="value">2</span></a></li>
</ul>
</dd>
</dl>
The DD
is set to be hidden when the GO link is clicked I have some code that slides the DD down or up. However my question is that when I have more than one instance if these in a page, one click opens all the DD
on the page, how can I target the DD that is closest to click,
I have tried the following,
$(".dropdown dt a").click(function(e) {
$(this).closest("dd").slideToggle(defaults.speed);
e.preventDefault();
});
and also this,
$(".dropdown dt a").click(function(e) {
$(this).next("dd").slideToggle(defaults.speed);
e.preventDefault();
});
I have had no success yet though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的想法是正确的,但是您尝试过的方法并没有按照您期望的方式发挥作用。最简单的选择可能是转到父级,然后找到适当的元素:
您的尝试因以下原因失败:
.closest
遍历 DOM(它向上查找,因此它检查父级,然后检查所有进一步的祖先,直到找到匹配项)。在您的情况下,所需的元素不是this
的祖先,因此这不起作用。.next
获取当前匹配元素的下一个同级元素。在您的情况下,没有后续同级元素,因为a
是dt
中的最后一个元素。请注意,如果您的 DOM 结构可能会更改,您可能需要使用
closest
来到达dl
元素,然后使用.find
来查找dd
(参见@Nicola Peluchetti 的回答)。You have the right idea, but the methods you've tried do not function quite the way you're expecting. The easiest option will probably be to go up to the parent and then find the appropriate element:
Your attempts failed for the following reasons:
.closest
traverses the DOM (it looks upwards, so it checks the parent, then all further ancestors until a match is found). In your case, the required element is not an ancestor ofthis
, so that won't work..next
gets the following sibling of the currently matched element. In your case, there isn't a following sibling as thea
is the last element in thedt
.Note that if your DOM structure is likely to change you may want to use
closest
to reach thedl
element, and then use.find
to find thedd
(see @Nicola Peluchetti's answer).您是否尝试过:
您不能使用 next() 因为您的链接只有一个 SPAN 作为同级,并且您不能使用最接近的,因为它只是沿着树向上走
Have you tried:
Youc't use next() because your link has only a SPAN as a sibling and you can't use closest because it just walks up the tree
尝试;
Try;