Removing jQuery and adding classes

I am trying to use jQuery to add / remove classes as part of a function that uses links to switch the main sections of content 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('selected');
   }

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

Here is the HTML sections 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 code for the links on the side of the page that control the switching of divs. The "selected" class should be removed from option 1 and added to any other link that the user selects, but this does not happen. The class does not change 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>

As I said above, I cannot change the "selected" class. Any suggestions?

+3
source share
2 answers

class , :

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

( , ):

<a href="#" id="1" class="link1 selected">Your Feed</a>
+4
$('.link1,.link2,.link3').bind('click', function() { $(this).toggleClass('selected'); });
+1

Source: https://habr.com/ru/post/1757903/


All Articles