[英]add/remove class with jQuery on link select
I'm trying to write a function in jQuery that will add a class to a selected link (which opens a page in an iframe) then remove that class when another link is selected. 我正在尝试在jQuery中编写一个函数,该函数会将一个类添加到选定的链接(在iframe中打开页面),然后在选择另一个链接时删除该类。 I received some help from another member here before for a similar type of thing, but that involved radio buttons and tables. 之前,我从另一个成员那里得到了一些类似类型的帮助,但其中涉及单选按钮和表格。
I tried playing with it for awhile, but jQuery is still pretty new to me so I don't know a whole lot about it. 我尝试玩了一段时间,但是jQuery对我来说仍然很新,所以我对此并不了解。
Basically, I have about 3-4 groups of links contained in <div id="CollapsiblePanelContent"> ... </div>
and I would like to add a style to the <a>
tag within this container that the user selected. 基本上,我在<div id="CollapsiblePanelContent"> ... </div>
包含大约3-4组链接,我想在用户选择的此容器内的<a>
标签中添加样式。
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you. 谢谢。
<div id="CollapsiblePanelContent">
<a href="page1.asp" onclick="return handlelink(this)">Link1</a>
<a href="page2.asp" onclick="return handlelink(this)">Link2</a>
<a href="page3.asp" onclick="return handlelink(this)">Link3</a>
<a href="page4.asp" onclick="return handlelink(this)">Link4</a>
</div>
<script type='text/javascript'>
$(function() {
$('div').click(function(event) {
$(this).closest('.CollapsiblePanelContent').addClass('selected').parent().siblings().each(function() {
$(this).find('.CollapsiblePanelContent').removeClass('selected');
});
});
});
</script>
$('#CollapsiblePanelContent a').on('click', function(e){
e.preventDefault(); // prevent page reload, you may remove it if don't need
$(this).addClass('selected').siblings().removeClass('selected');
});
As CollapsiblePanelContent
is id
so correct selector will be #CollapsiblePanelContent
not .CollapsiblePanelContent
. 由于CollapsiblePanelContent
是id
因此正确的选择器将是#CollapsiblePanelContent
而不是.CollapsiblePanelContent
。
But if you use CollapsiblePanelContent
for multiple div
s then instead of id
it should be class
with selector .CollapsiblePanelContent
. 但是如果你使用CollapsiblePanelContent
多div
当时的而不是id
应该是class
与选择.CollapsiblePanelContent
。 Because multiple elements can have same id
. 因为多个元素可以具有相同的id
。
You can try : 你可以试试 :
function handlelink(this)
{
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
//do the rest with the click
}
Based on the HTML you've provided the following should work: 根据HTML,您提供了以下功能:
$(function() {
$('.CollapsiblePanelContent a').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
});
That binds the click event handler to any <a>
elements inside <div class="CollapsiblePanelContent">
, which adds the selected
class to the clicked link, and removes the same class from all of its siblings. 这会将click事件处理程序绑定到<div class="CollapsiblePanelContent">
内的任何<a>
元素,这会将selected
类添加到被单击的链接中,并从其所有同级中移除相同的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.