我在Stack Overflow上发现了许多相关内容,但不适用于我的情况。
在这个例子中,我需要检查一个元素是否包含另一个元素,如果是,则附加一些内容。
$(".bt_repondre").click(function(){
comment = $(this).parent().parent().parent();
//I want to check if comment contains a .comment_full element, if no, append.
comment.append('add');
});
希望你能帮助我,我尝试了很多东西......
答案 0 :(得分:31)
您可以使用.has
和.length
:
if (comment.has('.comment_full').length) {
// It has that element
}
.find
将迭代所有后代,但.has
将在找到与选择器匹配的后代后停止。它可能运行得更快。
.length
只检查生成的元素集的长度是否为非零。
答案 1 :(得分:16)
只需使用.find()
并检查是否返回元素,如下所示:
$(".bt_repondre").click(function(){
comment = $(this).parent().parent().parent();
if (! comment.find('.comment_full').length) {
comment.append('add');
}
});
答案 2 :(得分:9)
大多数答案都不正确。您必须传递DOM节点而不是jQuery元素才能使$ .contains按https://api.jquery.com/jQuery.contains/正常工作。
例如,您可以确定$('#a')
是否包含$('#b)
。
HTML:
<div id="a">
<div id="b"></div>
</div>
JavaScript的:
var $a = $('#a');
var $b = $('#b');
var contains = $.contains($a.get(0), $b.get(0));
console.log('contains', contains);
// outputs `true`
答案 3 :(得分:1)
这些答案中的大多数都很棒,但有一个new method called contains(container,contained)
(在1.4中添加)会返回Boolean
!它与Blender的代码片段基本相同,但可能更快,无论是键入还是执行。
在您的代码中实现,它看起来像这样:
$(".bt_repondre").click(function(){
comment = $(this).parent().parent().parent();
if(!$.contains(comment, $('.comment_full')))//same as if(!jQuery.contains(...
{
comment.append('add');
}
});
答案 4 :(得分:1)
如果您正在寻找让我们说id为myTable的表中的任何tr元素,您可以使用以下代码:
if($('#productsTableBody tr').length)
{
//...
}
这样我们就可以检查wheather表中是否包含任何行。
答案 5 :(得分:0)
试试这个
comment.has('a.comment_full').length == 0
答案 6 :(得分:0)
这对我来说是这样的:
$(window).click(function(e) {
// if popup is visible
if($('.assignment_popup:visible').length) {
popup_id = $('.assignment_popup:visible').attr('id');
// if user clicked on popup itself or on something inside popup then do nothing
if($(e.target).hasClass('open-popup') || $(e.target).hasClass('assignment_popup')) {
return;
}
// if clicked element is not inside the popup then close the popup
if(!$('#' + popup_id).find(e.target).length) {
$('#' + popup_id).fadeOut(500);
}
}
//console.log(e.target);
});