jQuery选择器 - 除了第一个标签和输入之外的所有元素?

时间:2012-09-27 23:03:06

标签: jquery

我觉得我应该可以在这里使用:not(:first-child)选择器,但它似乎并不像我希望的那样工作。

http://jsfiddle.net/39KZ9/6/

我想让标签仍然出现。我怎样才能做到这一点?

<div id="OrdersSearchResult">
    <input type="radio" id="SearchResultsLink" name="SearchResultNavigation" checked="checked"/>
    <label id="SearchResultsLinkLabel" for="SearchResultsLink">Search Results</label>
</div>​

$(document).ready(function(){
    $('#OrdersSearchResult').children('label:not(:first-child)').remove();
    $('#OrdersSearchResult').children('input:not(:first-child)').remove();
});​

更新:就是这样,我很清楚,第一个子选择器会查找已匹配元素的第一个子节点。也就是说,我希望它选择所有不是第一个输入的输入,并且类似于标签。不幸的是,它与OrdersSearchResult的子元素的第一个子元素匹配,无论应用其他过滤器。

4 个答案:

答案 0 :(得分:2)

对标签和输入执行此操作:

var labels = $('#OrdersSearchResult > label').toArray();
labels.shift();
$(labels).remove();

或者也许:

$($('#OrdersSearchResult > label').toArray().shift()).remove();

答案 1 :(得分:2)

http://jsfiddle.net/39KZ9/16/

$(document).ready(function(){
    $('#OrdersSearchResult').children('label:gt(0)').remove();
    $('#OrdersSearchResult').children('input:gt(0)').remove();
});​

使用大于选择器。

:gt(0)基本上表示项目大于第一项,因为0的索引是第一个。

http://api.jquery.com/gt-selector/

顺便说一句:first-child返回父元素的第一个子元素而不是元素组中的第一个子元素。

更简单:

$(document).ready(function(){
    $('#OrdersSearchResult').children('label:gt(0),input:gt(0)').remove();
});​

答案 2 :(得分:1)

所以你已经删除了你的小提琴中的非第一子元素:标签。

我想您要删除包含输入和标签的非第一个字段组。在这种情况下,请查看http://jsfiddle.net/39KZ9/8/

答案 3 :(得分:1)

选择器:first-child允许您选择特定节点的第一个子节点。

在您的代码中,第一个孩子是第一个输入。所有其他节点都不是第一个子节点,因此,它将被您的jQuery调用删除。

为了解决您的问题,您必须将每个输入和标签分组到容器(<p>, <div>, ...)中,并在这些容器上应用jQuery调用。

相关问题