jQuery - 切换父元素的类?
我有一些列表元素,如下所示:
<li class="item">
<a class="toggle"><h4>ämne<small>2010-04-17 kl 12:54 by <u>nike1</u></small></h4></a>
<div class="meddel">
<span>
<img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
<a href="account.php?usr=47">nike1</a>
</span>
<p>text</p>
<span style="clear: both; display: block;"></span>
</div>
</li>
<li class="item odd">
<a class="toggle"><h4>test<small>2010-04-17 kl 15:01 by <u>nike1</u></small></h4></a>
<div class="meddel">
<span>
<img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
<a href="account.php?usr=47">nike1</a>
</span>
<p>test meddelande :) [a]http://youtube.com[/a]</p>
<span style="clear: both; display: block;"></span>
</div>
</li>
我正在尝试弄清楚如何制作它,以便当您单击类 .toggle 的链接时,父元素(li 元素)将切换类 .current。
我不确定以下代码是否正确,但它不起作用。
$(this).parent('.item').toggleClass('.current', addOrRemove);
即使我删除“('.item')”,它似乎也没有任何区别。
那么,有什么想法吗?
提前致谢
I have a few list elements, like this:
<li class="item">
<a class="toggle"><h4>ämne<small>2010-04-17 kl 12:54 by <u>nike1</u></small></h4></a>
<div class="meddel">
<span>
<img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
<a href="account.php?usr=47">nike1</a>
</span>
<p>text</p>
<span style="clear: both; display: block;"></span>
</div>
</li>
<li class="item odd">
<a class="toggle"><h4>test<small>2010-04-17 kl 15:01 by <u>nike1</u></small></h4></a>
<div class="meddel">
<span>
<img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
<a href="account.php?usr=47">nike1</a>
</span>
<p>test meddelande :) [a]http://youtube.com[/a]</p>
<span style="clear: both; display: block;"></span>
</div>
</li>
And i'm trying to figure out how to make it so that when you click a link with the class .toggle, the parent element (the li element) will toggle the class .current.
I'm not sure if the following code is correct or not, but it's not working.
$(this).parent('.item').toggleClass('.current', addOrRemove);
Even if i remove "('.item')", it doesn't seem to make any difference.
So, any ideas?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
toggleClass
采用类名,而不是选择器。因此,您不应包含.
.将其更改为
toggleClass('current')
(不带.
)。此外,您可以通过调用
closest
而不是parent
来使代码更加健壮。closest
将搜索与选择器匹配的最里面的父元素,这样,如果链接嵌套在.item
内,它将继续工作。toggleClass
takes a class name, not a selector. Therefore, you shouldn't include a.
.Change it to
toggleClass('current')
(without a.
).Also, you can make your code more robust by calling
closest
instead ofparent
. Theclosest
will search for the innermost parent element that matches the selector, so that it will keep working if the link is nested inside the.item
.