简体   繁体   中英

jQuery addClass to list item

I have multiple pages that all use a simple tab menu at the top. The menu (aka list) is stored in a separate html file:

<ul>
  <li id="Tab1"><a href='../Page1.html'> Page1 </a></li>
  <li id="Tab2"><a href='../Page2.html'> Page2 </a></li>
  <li id="Tab3"><a href='../Page3.html'> Page3 </a></li>

every page has <div id='tabs'> </div> and

$('#tabs').load('CommonTabs.html');

Everything works fine, my tabs load into the 'tabs' div. Now I want to set a class of one div on each page to "active", so that the proper style defined in a css can be applied. I tried:

$('#tabs').load('CommonTabs.html');
$('#Tab1'.addClass("active");

But that doesn't seem to work. When I do "inspect element" in a browser, the li does not have the "active" class assigned.

The load function is asynchronous, so the data is not loaded when the second call executes. Perform it in a callback function instead:

$('#tabs').load('CommonTabs.html', function () {
    $('#Tab1').addClass("active");
});

You have a syntax error. Try: $('#Tab1').addClass("active");

I will give you an example to set a class to a specific element on a button click. Of course you will need to create a button with the class addClassButtonTab3 for this to work.

$('.addClassButtonTab3').click('on', function() {
    $('#tab3').addClass('active');
});

We are binding an event handler to a button with class 'addClassButtonTab3' and when it is clicked we are adding a class to an element with ID tab3.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM