Jquery Traverse DOM

时间:2013-08-09 08:51:50

标签: jquery dom dom-traversal jquery-traversing

我有以下代码:

<p class="represent">Representing</p>
<div class="clients_wrap">
    <ul class="clients">
        <li><img src="{{ client.get_sized_image }}"></li>
    </ul>
</div>

这个块重复多次。列表项的数量可以在0到10+之间变化,但是如果它是0,那么我需要隐藏它之前的p.represent标记 - 这对于每个重复的代码块都需要是独立的。

我已经尝试过很多东西,但不能完全弄清楚,例如。

function hideEmptyClients() {
    if ( $('ul.clients li').length >= 1 ) {
        $('ul.clients').parent().closest('p').hide();
    }
}
$(function() {
    hideEmptyClients();
});

解决: Tomalak提供的最佳解决方案:

$(function () {
    $('ul.clients:not(:has(li))').closest(".represent_wrap").hide();
});

2 个答案:

答案 0 :(得分:0)

首先,您所拥有的逻辑似乎与您描述的内容相反 - 如果找到多个p元素,则隐藏li元素,而不是如果没有。其次,closest()查看父元素,其中pdiv的兄弟,因此您需要使用prev()。试试这个:

$('.clients').each(function() {
    var $ul = $(this);
    if (!$('li', $ul).length) {
        $ul.closest('.clients_wrap').prev('p').hide();
    }
});

答案 1 :(得分:0)

$(function() {
    $('p.represent').filter(function () {
        return $(this).next("clients_wrap").find("li").length === 0;
    }).hide();
});

这背后的基本原理遵循jQuery范例:

  1. 选择一些内容($('p.represent')
  2. 可选择过滤它(.filter(...)
  3. 对此做些什么(.hide()
相关问题