简体   繁体   中英

How to add a class to an element when thead table was click in jquery?

I want to add a class Open to li element on class Menus when user click on thead tr th of my table as below.

This is my table

<div><ul>
 <li class="menus">
    <a></a>
    <ul><li>
     <table id="tableid ">
        <thead>
          <tr><th></th><th></th><th></th></tr>
        </thead>
        <tbody>
            <tr id="1">
                <td></td>
                <td id="type1">types1</td>
                <td></td>
                <td id="types2">types2</td>
                <td></td>
            </tr>
            <tr id="2">
                <td></td>
                <td id="type1">types3</td>
                <td></td>
                <td id="types2">types4</td>
                <td></td>
            </tr>
           </tbody>
       </table>
    </li>
  </ul>
</li></ul></div>

JS

$(document).on('click','#tableid thead tr th', function(){
    var parents = $(this).prevAll().find('li')
    console.log(parents)

});

Use .parents and .addClass

$(document).on('click','#tableid thead tr th', function(){
    var parents = $(this).parents('li.menus').addClass('open')
    console.log(parents)
});

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