1

这是我的问题:

我有一个包含在主容器中的元素列表,如下所示:

<span class="main_container">
    <span id=".." class=".." position="1"...> </span>
    <span id=".." class=".." position="2"...> </span>  
    <span id=".." class=".." position="3"...> </span>
    <span id=".." class=".." position="4"...> </span>
    <span id=".." class=".." position="5"...> </span>
    <span id=".." class=".." position="6"...> </span>
</span>

我将 ID 和位置用于不同的目的。现在,当我单击位置 4 的元素时,我希望系统删除跨度 4 及其下方的所有跨度。即5、6。

jQuery 我该怎么做?我试过.parents()了,但没有做到。

谢谢

4

2 回答 2

3

你想用这个:

http://api.jquery.com/nextAll/

$('.main_container').find('span').click(function(){
  var jq_this = $(this);
  jq_this.nextAll().remove();  // remove all later siblings
  jq_this.remove();            // removes self
});
于 2013-04-24T00:09:38.740 回答
1

Bind .click() on the child spans, use .index() to get its sequence index, then use :gt() selector to find elements past it and use .add()

$('.main_container span').click(function(){
    // get position of current element
    var index = $(this).index();
    // delete this and all elements past this element
    $(this).parent().find('span:gt('+index+')').add(this).remove();
});

Example: http://jsfiddle.net/cDZqk/

You can also use .children() if there's more nesting going on:

$('.main_container span').click(function(){
    // get position of current element
    var index = $(this).index();
    // delete this and all elements past this element
    $(this).parent().children(':gt('+index+')').add(this).remove();
});

Example: http://jsfiddle.net/cDZqk/1/

or, ya know, you can use .nextAll and let it take care of it for you. :curses:

The "one-liner" version of BYossarian's answer:

$('.main_container span').click(function(){
    $(this).nextAll().add(this).remove();
});

Example: http://jsfiddle.net/cDZqk/2/

于 2013-04-24T00:05:26.897 回答