JQuery $ (this) task

I am writing several jQuery codes as shown below:

$('.button').each(function(){
    $(this).click(function(){
        console.log($(this));
        do_sth();
    });
});

var do_sth = function(){
    console.log($(this));
}

I want the console.log results to be the same, but it doesn’t work correctly ... The first relates to HTMLElement, and the second refers to DOMWindow ... How can I rewrite the do_sth function so that they all refer to HTMLElement? Thank.

+3
source share
5 answers

You can do...

do_sth.call(this);

Alternatively, you can use the jQuery method proxy().

$.proxy(do_sth, this)();

jsFiddle .

+9
source

1. You can make this a prototype function:

$.fn.do_sth = function() { console.log( this ); };

In another fn just do $(this).click(function() { $(this).do_sth(); });

2. You can use.call

do_sth.call(this);

3. You can change it to expect an element parameter:

function do_sth( el ) { console.log( el ) }
+4
source

:

$('.button').click(function() {
        do_sth.call(this);
    });
});
+1

.

$('.button').each(function(){
    $(this).click(function(){
        console.log($(this));
        do_sth(this);
    });
});

var do_sth = function(button){
    console.log(button);
}

: http://jsfiddle.net/JfwNJ/

0

do_sth, $(this) :

var do_sth = function($el) {
  console.log($el)
}

:

$('.button').each(function(){
    var $that = $(this);
    $(this).click(function(){
        console.log($that);
        do_sth($that);
    });
});
0

All Articles