繁体   English   中英

检查是否有 <select>在父div中

[英]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'(除了像0undefined等值之外的所有东西), if条款被执行,你可以安全地消除> 0

if($(this).parent().find("select").length) {
    // there is one, display something
}

http://api.jquery.com/length/

http://api.jquery.com/parent/

http://api.jquery.com/find/

是的,检查结果集数组的length属性。

if ($('#parentDiv select').length > 0) {
    alert('There is at least one <select> inside the div!');
}

jsFiddle工作示例

使用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.

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