jQuery DOM 遍历
我一直在尝试将 $.click 处理程序绑定到同级元素,但似乎找不到正确选择要设置动画的元素的方法。以下是我正在使用的 DOM 树的基本结构:
<section id="a">
<div id="b" class="foo" draggable="true">
<header style="cursor:pointer;">1.</header>
<p class="foo">Bar</p>
</div>
<div id="c" class="foo" draggable="true">
<header style="cursor:pointer;">2.</header>
<p class="foo">Bar</p>
</div>
<!-- and so on... -->
</section>
现在,当用户单击
时,我想要同级
> 执行
jQuery.slideToggle()
。此时,我有以下 JavaScript,但无济于事:
$('header').click(function() {
$(this).parent().children("p").slideToggle('slow');
// I also tried:
$(this).parent().children("p.foo").slideToggle('slow');
// but as I expected, there was no difference.
});
因此为了澄清,一个非常冗长的版本将是:
$('div#b.foo header').click(function(){
$('div#b.foo p.foo').slideToggle('slow');
});
$('div#c.foo header').click(function(){
$('div#c.foo p.foo').slideToggle('slow');
});
// ...
如果这还不够清楚,请让我详细说明。
I've been trying to bind a $.click
handler to a sibling element, but can't seem to find a way to properly select the element to animate. Here is the basic structure of the DOM tree that I'm working with:
<section id="a">
<div id="b" class="foo" draggable="true">
<header style="cursor:pointer;">1.</header>
<p class="foo">Bar</p>
</div>
<div id="c" class="foo" draggable="true">
<header style="cursor:pointer;">2.</header>
<p class="foo">Bar</p>
</div>
<!-- and so on... -->
</section>
Now, when a user clicks a <header>
, I would like the sibling <p>
to perform a jQuery.slideToggle()
. At this point, I have the following JavaScript, but to no avail:
$('header').click(function() {
$(this).parent().children("p").slideToggle('slow');
// I also tried:
$(this).parent().children("p.foo").slideToggle('slow');
// but as I expected, there was no difference.
});
So to clarify, a very drawn-out version of this would be:
$('div#b.foo header').click(function(){
$('div#b.foo p.foo').slideToggle('slow');
});
$('div#c.foo header').click(function(){
$('div#c.foo p.foo').slideToggle('slow');
});
// ...
Please ask me to elaborate if this is not clear enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试
实时示例
.next
You can try
Live Example
.next
我通过在文档就绪时初始化单击处理程序解决了该问题。解决方法如下:
I resolved the issue by initializing the click handler on document ready. The solution is as follows: