开发者

JQuery removing and adding classes

开发者 https://www.devze.com 2023-01-10 15:08 出处:网络
I\'m trying to use JQuery to add/remove classes as part of a function that uses links to switch around the main content divs on my site.

I'm trying to use JQuery to add/remove classes as part of a function that uses links to switch around the main content divs on my site.

Here is my JavaScript:

$(document).ready(function () {
  var clickHandler = function (link) {
     $('.tab').hide();
     $('#options_' + link.data.id).show();
     $('.selected').removeClass('selected');
     $(this).addClass('selecte开发者_如何学Pythond');
   }

   $('.link1').bind('click', {id:'1'}, clickHandler);
   $('.link2').bind('click', {id:'2'}, clickHandler);
   $('.link3').bind('click', {id:'3'}, clickHandler);
});

Here is the HTML of the divs I'm switching (this part works):

<div id="options_1" class="tab">
<h3>Your Feed</h3>
<?= $userFeed ?></div>

<div id="options_2" class="tab">
<h3>All Recent Activity</h3>
<?= $feed ?>

</div>
<div id="options_3" class="tab">
<h3>Trends</h3>
Coming Soon!
</div>

And here is the HTML of the links in the sidebar portion of the page that control the div switching. The class "selected" should be removed from option 1 and added to whatever other link the user selects, but this isn't happening. The class isn't being changed at all.

<ul id="feedOptions">
<li><a href="#" id="1" class="link1" class="selected">Your Feed</a></li>
<li><a href="#" id="2" class="link2">All Activity</a></li>
<li><a href="#" id="3" class="link3">Trends</a></li>
</ul>

Like I said above, I can't get the 'selected' class to change at all. Any suggestions?


You have multiple class attributes on a single element, instead of this:

<a href="#" id="1" class="link1" class="selected">Your Feed</a>

You should have this (single attribute, separate classes with a space):

<a href="#" id="1" class="link1 selected">Your Feed</a>


$('.link1,.link2,.link3').bind('click', function() { $(this).toggleClass('selected'); });
0

精彩评论

暂无评论...
验证码 换一张
取 消