简体   繁体   中英

Selecting a number of siblings in jQuery

When a user clicks on a <td> in a table, I want to apply a css class to it. I also want to apply a css class to its siblings and apply another css class to the last sibling. The following code will achieve this...

$('td.sel').addClass('first').siblings().addClass(‘middle').last().addClass('last’);

But what I want to do is apply the css class to a particular number of siblings - not all of them .

For example, if I had the following table

<table>
    <tr>
        <td data-num="3">monday</td>
        <td data-num="2">tuesday</td>
        <td data-num="3">wednesday</td>
        <td data-num="2">thursday</td>
        <td data-num="1">friday</td>
        <td data-num="3">saturday</td>
        <td data-num="1">sunday</td>
    </tr>
</table>

…and if a user clicks the <td> with Wednesday then...

  1. Add the class ".first" to the clicked <td>
  2. With the data-num value, count the next siblings to apply the class ".middle" to. var numberOfDays = $(this).attr("data-num");
  3. Add a different class to the last ".last" sibling

So the table would now look like this

<table>
    <tr>
        <td data-num="3">Monday</td>
        <td data-num="2">Tuesday</td>
        <td data-num="3" class="first" >Wednesday</td>
        <td data-num="2" class="middle">Thursday</td>
        <td data-num="1" class="middle">Friday</td>
        <td data-num="3" class="last" >Saturday</td>
        <td data-num="1">Sunday</td>
     </tr>
</table>

Any advise or help on how to do this is appreciated.

EDIT:

I created a JSFiddle demonstrating what I am trying to do. It actually works, but the code is poor. I would also need to check if its the very last <td> in the table, then apply the .last class. https://jsfiddle.net/5to9hewo/109/

A possible alternative is to keep the days, slice the days following the index, without the index itself and then slice all but the last to add the middle class. This way, the last element itself will not be affected, and by using last on the first object, the last actually existing object will be used: Fiddle

var days = $("td.day").click(function() { //assign days and attach the click in one go
  days.removeClass('first last middle');  

  var start = days.index(this),
    end = start + parseFloat($(this).addClass('first').data("num")) ,
    next =  days.slice(++start,end); 
  next.slice(0,end-start-1).addClass('middle');
  next.last().addClass('last');
});

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