我使用 id 来获取孩子,现在我改为使用类。 这样做我发现使用类不会返回孩子。
工作代码
//Don't remove first element of select box with id 'someSelectBox'
$('#someSelectBox').children('option:not(:first)').remove();
不工作代码
//Don't remove first element of ALL select box with class 'selectBoxClass'
$('.selectBoxClass').children('option:not(:first)').remove();
谁能解释为什么?以及可能的锻炼或替代实施想法。
谢谢
如果要排除每个select
元素的前option
,则需要使用.children('option:not(:first-child)')
(这是因为您定位的是多个select
元素,并且:first
仅适用于整个结果集中的第一个)
否则,仅排除第一个select
元素的前option
。
该类应该不会产生任何问题
var options = $('.select-to-include').children('option:not(:first-child)');
options.css({color:'red'});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="select-to-include">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="select-to-include">
<option>1</option>
<option>2</option>
<option>3</option>
</select>