I need a script that adds a 2 to the end of a class in a div with the id .sideboxtopleft on clicking of a link with the id of posts.
<script>
$(".posts").click(function () {
if ($('.sideboxtopleft').is('#sideboxtopleft2')) {
$('.sideboxtopleft').removeClass('2');
}
else{
$('.sideboxtopleft').addClass('2');
}
});
</script>
<div id="sideboxtopleft" class="sideboxtopleft">
<a href="#post" id="posts"><h3>R开发者_高级运维ECENT POSTS <div id="arrow" class="arrow"></div></h3></a>
</div>
<div id="sideboxtopright" class="sideboxtopright">
<a href="#comments" id="comments"><h3>RECENT COMMENTS <div id="arrow" class="arrow2"></div></h3></a>
</div>
However it doesn't seem to want to work properly. Any help?
You can do it using .toggleClass()
like this:
$(".posts").click(function () {
$('.sideboxtopleft, .sideboxtopleft2').toggleClass('sideboxtopleft sideboxtopleft2');
});
All of the class methods add, remove, or toggle entire classes, they don't append/remove part of a class name. Though the above code works, it isn't the most ideal solution, a multi-class selector in CSS is probably a better approach, like this:
.sideboxtopleft { color: black; }
.sideboxtopleft.on { color: red; }
Then you could just toggle the on
class, like this:
$(".posts").click(function () {
$('.sideboxtopleft').toggleClass('on');
});
Why not just add a new class to tag?
<div id='foo' class='sideboxtopleft two'>
精彩评论