[英]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.