我使用以下内容将所有项目包含在一个'child'类中,并使用一个带有'parent'类的div:
$(".child").wrapAll('<div class="parent" />');
问题是该函数有时会重新运行,我不希望创建多个div.parents'。如何在我的代码中添加一个条件,这样只有在div.childs不具有父类的“父”时才添加div.parent?谢谢
答案 0 :(得分:1)
您可以像这样使用hasClass()
:
if (! $(".child").parent().hasClass('parent')){
$(".child").wrapAll('<div class="parent" />');
}
或closest
使用length
:
if (! $(".child").closest('.parent').length){
$(".child").wrapAll('<div class="parent" />');
}
答案 1 :(得分:0)
不知道是不是很快:
$(":not(.parent) > .child").wrapAll('<div class="parent" />');
未经测试!!但可以工作
答案 2 :(得分:0)
你可以单行完成)
$( “子 ”)的父母。(“ 子”)。( 'P不是(.parent)')找到wrapAll( '');