最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery .nextAll() is not working with html table columns - Stack Overflow

programmeradmin2浏览0评论

I have a html table as below:

<table>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
    </tr>
    <tr>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
    </tr>
</table>

On click of a td I am changing the color of it's next 4 td's and for that I have done it in jquery as below:

$(this).nextAll("td").slice(0, 4).addClass("selected");

Above code is working if I click on 1st TD then it selects further 4 td's but if I click on 4th td then it selects only 5th td. I want it to select another 3 td's in next row as well.

Please tell me how can I fix this?

I have a html table as below:

<table>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
    </tr>
    <tr>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
    </tr>
</table>

On click of a td I am changing the color of it's next 4 td's and for that I have done it in jquery as below:

$(this).nextAll("td").slice(0, 4).addClass("selected");

Above code is working if I click on 1st TD then it selects further 4 td's but if I click on 4th td then it selects only 5th td. I want it to select another 3 td's in next row as well.

Please tell me how can I fix this?

Share Improve this question asked Sep 13, 2013 at 9:23 djmzfKnmdjmzfKnm 27.2k70 gold badges173 silver badges234 bronze badges 2
  • Can you create jsfiddle of your code? – Saranya Sadhasivam Commented Sep 13, 2013 at 9:29
  • From api.jquery./nextAll "Get all following siblings of each element in the set of matched elements, optionally filtered by a selector." The important thing to not is that it gets all following siblings – NinjaNye Commented Sep 13, 2013 at 11:03
Add a ment  | 

3 Answers 3

Reset to default 10

jQuery .index() method returns the index of passed element in the current set. By using returned index you can .slice() the collection, this is more efficient than querying the DOM on each click, especially when you have a big table:

var $tds = $('#table td').on('click', function() {
   var i = $tds.index(this);
   $tds.slice(++i, i+4).addClass("selected");
});

http://jsfiddle/MamYX/

You can simply add the td of the following row. :

$(this).nextAll("td").add($(this).closest('tr').nextAll().find('td'))
       .slice(0, 4).addClass("selected");

Demonstration

var $tds = $('table td').click(function(){
    var idx = $tds.index(this);
    $tds.filter(':gt(' + idx + '):lt(4)').addClass('selected')
})

Demo: Fiddle

发布评论

评论列表(0)

  1. 暂无评论