检查父div中是否有<select>

Hen*_*nry 3 html javascript jquery

我怎么能做这样的事情:检查我是否<select>在父div中有一个,如果有,我会显示一些东西.

谢谢!

Gab*_*oli 8

一种方法是使用:has选择器进行过滤

if ( $(this).parent(':has(select)').length ){
  // display something..
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果select不比当前元素更深,则可能需要使用该.siblings()方法

if ( $(this).siblings('select').length ){
  // display something..
}
Run Code Online (Sandbox Code Playgroud)


pim*_*vdb 7

如果有,则包含匹配元素的jQuery对象的长度为> 0.因为if当条件为"truthy"(一切,除了像值条款得到执行0,undefined等等),你是安全的消除> 0:

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

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

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

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