繁体   English   中英

用jQuery看一个div有没有某某的子class

[英]Using jQuery to see if a div has a child with a certain class

我有一个 div #popup ,它用 class .filled-text动态填充了几个段落。 我试图让 jQuery 告诉我#popup中是否包含这些段落之一。

我有这个代码:

$("#text-field").keydown(function(event) {
    if($('#popup').has('p.filled-text')) {
        console.log("Found");
     }
});

有什么建议么?

您可以使用find功能:

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

有一个hasClass函数

if($('#popup p').hasClass('filled-text'))

使用儿童的jQuery funcion。

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length将返回与选择器匹配的子元素的数量。

简单的方法

if ($('#text-field > p.filled-text').length != 0)

如果它是一个直接的孩子,你可以做如下,如果它可以嵌套更深,删除>

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

如果您有多个具有相同类的 div 并且有些只有该类,则必须检查每个:

            $('.popup').each(function() {
                if ($(this).find('p.filled-text').length !== 0) {
                    $(this).addClass('this-popup-has-filled-text');
                }
            });

自您提出这个问题以来的 10 年中,jQuery 几乎完全添加了您上面描述的.has( function 。它过滤了它所调用的选择器 - 它比使用$('.child').parent('.parent')更快。 $('.child').parent('.parent')并可能一直运行到 DOM。

$("#text-field").keydown(function(event) {
    if($('#popup').has('p.filled-text').length) {
        console.log("Found");
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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