繁体   English   中英

在jQuery中让孩子通过id vs class

[英]Getting children through id vs class in jQuery

我当时用id来生孩子,现在我改用了class。 这样做我发现使用类不会返回孩子。

工作代码

//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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM