Domanda

I have the following code:

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

This chunk is repeated a number of times. The number of list items may vary between 0 and 10+, but if it is 0 then I need to hide the p.represent tag that precedes it – this needs to be independant for each repeated code block.

I've tried a number of things but can't quite figure it out e.g.

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

SOLVED: Best solution provided by Tomalak:

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

Soluzione

Firstly the logic you have seems backwards to what you describe - you're hiding the p element if there are multiple li elements found, not if there are none. Secondly, closest() looks at parent elements, where as the p is a sibling of the div, so you'd need to use prev() instead. Try this:

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

Altri suggerimenti

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

The rationale behind this follows the jQuery paradigm:

  1. select something ($('p.represent'))
  2. optionally filter it (.filter(...))
  3. do something to it (.hide())
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top