Select label through .find

3

I'm trying to create / adapt a tree list , however I'm not able to expand my list by clicking on a label.

List:

<div id="listContainer">
  <ul id="expList">         
    <li style="">
        <label style="margin-top: 50px;border-style: solid;  border-width: 1px; border-color: #7C7C7C; background-color:#E0E0E0">
        Item A
        </label>
            <ul>
                <li>
                    itens lista A
                </li>
            </ul>
    </li>
</ul>

Starting the error starts from my js function to expand the list:

function prepareList() {
        $('#expList').find('li:has(ul)')
        .click(function (event) {
            if (this == event.target) {
                $(this).toggleClass('expanded');
                $(this).children('ul').toggle('medium');
            }
            return false;
        })
        .addClass('collapsed')
        .children('ul').hide();

...
...
}

I have tried to find the label in expList just to test and I could not solve the question:

$('#expList').find('label')
        .click(function (event) {
...
...
}

Follow the complete code: jsfiddle

PS.- If you click outside the list, it expands

    
asked by anonymous 19.09.2014 / 11:04

1 answer

3

There is a difference between using this and event.target inside an event dropper.

If the observer is tied to an element without descendants, then this == event.target . But in case the event is associated / tied to a relative then event.target will be the descending element of the initial, the one that received the click. The event will then go up in the DOM (bubbling) until it reaches the event handler which is then activated by having as this the element that is in the selector.

In your case the this will always be a li , as requested by the li:has(ul) selector, and the event.target <label> . There may be cases where event.target == li . In case you have a large padding and the user clicks outside the limits of label and still within li . But in any case the this will be given the li in question.

Looking at this example with background color in li you can see when this == li

    
19.09.2014 / 11:38