[英]check if there is a <select> within the parent div
我怎么能这样做:检查父div中是否有<select>
,如果有,我会显示一些东西。
谢谢!
一种方法是使用:has
选择器进行过滤
if ( $(this).parent(':has(select)').length ){
// display something..
}
另一方面,如果select
不比当前元素深,则可能需要使用.siblings()
方法
if ( $(this).siblings('select').length ){
// display something..
}
如果有,则包含匹配元素的jQuery对象的长度为> 0
。 因为if
条件是'truthy'(除了像0
, undefined
等值之外的所有东西), if
条款被执行,你可以安全地消除> 0
:
if($(this).parent().find("select").length) {
// there is one, display something
}
是的,检查结果集数组的length属性。
if ($('#parentDiv select').length > 0) {
alert('There is at least one <select> inside the div!');
}
使用jquery,您可以选择嵌套元素。
尝试这样的事情。
if( 0 < $('select', $('#div_id') ).length ) {
alert( 'Select box in the div' );
} else {
alert( 'NO Select box in the div' );
}
您也可以使用最接近的函数
<html>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
if($("#txt").closest("div").find("select").length){
alert("Found it");
}
});
</script>
<div>
<select id="heart"><option value="Hello"></option></select>
<input type="text" id="txt" />
</div>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.