I am trying to apply the following jQuery click function but for some reason I can't seem to get the selector right, i.e.:
$("ul.menu li a").click(function(){
$("ul.menu li").find("a").removeAttr("id");
$(this).attr("id" , "current" );
});
This is my HTML code I am trying to apply it to, i,e,:
<div id="sidebar">
<ul class="menu noaccordion">
<li>
开发者_运维知识库 <a href="#" id="current" class="topm">Home</a>
</li>
<li>
<a href="#" class="topm">About Us</a>
</li>
My aim is to try and set the current menu selected using the id=current.
How about this?
$("ul.menu li a").click(function(){
$(".topm").attr('id', '');
$(this).attr("id" , "current" );
});
I wouldn't remove the ID of the element. The ID attribute is designed to represent a single element in the DOM. You should really apply this with a class instead:
$("ul.menu li a").removeClass("currentMenu");
$(this).addClass("currentMenu");
So in your example:-
$("ul.menu li a").click(function() {
$("ul.menu li a").removeClass("currentMenu");
$(this).addClass("currentMenu");
});
You don't need to use each, as the removeClass action will be applied to each jquery result from the selector.
I would recommend you to use a class name that indicates that a menu is selected instead of id:
<ul>
<li>
<a href="#" class="topm selected">Home</a>
</li>
<li>
<a href="#" class="topm">About Us</a>
</li>
</ul>
Then your click function might look like this:
$('ul a').click(function() {
$('ul a').removeClass('current');
$(this).addClass('current');
});
I managed to get it going from my original code plus the addition of a .find("a")
on the last line, which has solved my problem, i.e.
$("#sidebar ul.menu li").click(function() {
$("ul.menu li").find("a").removeAttr("id");
$(this).find("a").attr("id" , "current" );
});
精彩评论