[英]check if there is a <select> within the parent div
How can I do something like this: check if I have a <select>
within the parent div, if there is one, I display something. 我怎么能这样做:检查父div中是否有
<select>
,如果有,我会显示一些东西。
Thanks! 谢谢!
One way would be to filter with the :has
selector 一种方法是使用
:has
选择器进行过滤
if ( $(this).parent(':has(select)').length ){
// display something..
}
If on the other hand the select
is not deeper than the current element, you might want to use the .siblings()
method 另一方面,如果
select
不比当前元素深,则可能需要使用.siblings()
方法
if ( $(this).siblings('select').length ){
// display something..
}
If there is one, the length of the jQuery object containing matched elements is > 0
. 如果有,则包含匹配元素的jQuery对象的长度为
> 0
。 Because if
clauses get executed when the condition is 'truthy' (everything except values like 0
, undefined
etc) you are safe to eliminate the > 0
: 因为
if
条件是'truthy'(除了像0
, undefined
等值之外的所有东西), if
条款被执行,你可以安全地消除> 0
:
if($(this).parent().find("select").length) {
// there is one, display something
}
http://api.jquery.com/length/ http://api.jquery.com/length/
Yes, check the length property of the result set array. 是的,检查结果集数组的length属性。
if ($('#parentDiv select').length > 0) {
alert('There is at least one <select> inside the div!');
}
with jquery you can select nested elements. 使用jquery,您可以选择嵌套元素。
try something like this. 尝试这样的事情。
if( 0 < $('select', $('#div_id') ).length ) {
alert( 'Select box in the div' );
} else {
alert( 'NO Select box in the div' );
}
You can also use function closest 您也可以使用最接近的函数
<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.