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. 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.
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.
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
.
But if you use CollapsiblePanelContent
for multiple div
s then instead of id
it should be class
with selector .CollapsiblePanelContent
. Because multiple elements can have same 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:
$(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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.