JQuery with multiple choices with "this"

The question about 'i' and 'this' matters. First, the icon was added behind the button. Second, the icon was added in front of the button. Why is this?

example 1:

$('.btn').click(function(){
    $('i', this).removeClass().addClass("icon-down");
})

      

Example 2:

$('.btn').click(function(){
    $(this, 'i').removeClass().addClass("icon-down");
})

      

+3


source to share


1 answer


It is clear that the two forms you use will generate different results.

$('i', this)

      

This form will find any elements <i>

that are children of the element it points to this

. it is structurally equivalent $(this).find('i')

, which is my preferred way of writing it because I find it more readable.

From the jQuery doc, this form is documented as jQuery( selector [, context ] )

.


Your other form:



$(this, 'i')

      

is not a directly supported option for a jQuery function, as there are no documented parameters that take (element, string)

. I'll check the jQuery code, but this will most likely be interpreted as a form $(element)

and hence simple $(this)

, and the second argument will be ignored. This parameter is documented as jQuery( element )

. The second argument is ignored if the first argument is a DOM element.

So the first option finds the children <i>

. The second option only works on the button itself.

The EDIT: . By examining the jQuery source code, I have confirmed that it is $(this, 'i')

handled the same as $(this)

. In fact, this is the operative part of the jQuery function:

init: function( selector, context, rootjQuery ) {
    if ( typeof selector === "string" ) {
        // handle selector string here    
        // ...

    // HANDLE: $(DOMElement)
    } else if ( selector.nodeType ) {
        this.context = this[0] = selector;
        this.length = 1;
        return this;
    }

      

+1


source







All Articles