Question: Jquery each inside onclick event

Question

Jquery each inside onclick event

Answers 2
Added at 2016-12-26 01:12
Tags
Question

Razor/HTML (many of these):

<div class="directory-item" id="@item_id" name="@item_name" style="padding-left: @(indent_level)px;  display: @(display)">
   <i class="fa @icon_type"></i>
   @item.ItemName (id: @item_id, name: @item_name, level: @item.Level)
   <i class="fa  fa-angle-right float-right"></i>
</div>

Javascript:

$(".directory-item").click(function () {
    $('div[name*=' + this.id + ']').each(function () {
        if (this.attr('display') == "none") {
            this.show();
        } else {
            this.hide();
        }
    });
});

Basic question: how do you put an "each" inside a "click" event and reference the "each" item (each time it accesses an element) with "this"? Maybe I shouldn't be using an each statement but something else?

Answers
nr: #1 dodano: 2016-12-26 02:12

In the each method's callback, you can have 2 parameters, one for the index and second for the item of current iteration of the loop.

$(function () {

    $(".directory-item").click(function () {

        $('div[name*=' + this.id + ']').each(function (a,b) {
            if ($(b).attr('display') == "none") {
                $(b).show();
            } else {
                $(b).hide();
            }
        });
    });
});

If it simply updating the visibility, you can use toggle as well

$('div[name*=' + this.id + ']').each(function (a,b) {
    $(b).toggle();
});
nr: #2 dodano: 2016-12-26 02:12

Assuming that there are elements with names that do match the id of element clicked you should be able to simplify this to:

$(".directory-item").click(function () {
        $('div[name*=' + this.id + ']').toggle()
});

Using toggle() will show such element if it is hidden and hide it if it is not and there is no need for each as it will loop through all matching elements internally

Source Show
◀ Wstecz