Javascript 使用 jQuery 查看 div 是否具有某个类的子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10539162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery to see if a div has a child with a certain class
提问by Samsquanch
I have a div #popup
that is dynamically filled with several paragraphs with the class .filled-text
. I'm trying to get jQuery to tell me if #popup
has one of these paragraphs in it.
我有一个 div#popup
动态填充了几个带有 class 的段落.filled-text
。我试图让 jQuery 告诉我其中是否#popup
有这些段落之一。
I have this code:
我有这个代码:
$("#text-field").keydown(function(event) {
if($('#popup').has('p.filled-text')) {
console.log("Found");
}
});
Any suggestions?
有什么建议?
回答by Tejs
回答by Christopher Ramírez
Use the childrenfuncion of jQuery.
使用jQuery的children函数。
$("#text-field").keydown(function(event) {
if($('#popup').children('p.filled-text').length > 0) {
console.log("Found");
}
});
$.children('').length
will return the count of child elements which match the selector.
$.children('').length
将返回与选择器匹配的子元素的计数。
回答by Hitesh Modha
Simple Way
简单的方法
if ($('#text-field > p.filled-text').length != 0)
回答by Rune FS
If it's a direct child you can do as below if it could be nested deeper remove the >
如果它是一个直接的孩子,如果它可以嵌套得更深,你可以按照下面的操作删除 >
$("#text-field").keydown(function(event) {
? ? if($('#popup>p.filled-text').length !== 0) {
? ? ? ? console.log("Found");
? ? ?}
});