Mark
Mark

Reputation: 33571

jquery: Passing this to child function

I have something like this:

$('element.selector').live("click", function (){
    run_some_func ();
});

$('element.selector2').live("click", function (){
    run_some_func ();
});

Now in the function I need to use $(this):

function run_some_func () {
    $(this).show();
}

How do I get the function to know that $(this) is element.selector that is clicked?

Thanks.

Upvotes: 0

Views: 908

Answers (2)

Colin Brock
Colin Brock

Reputation: 21565

Can't you pass $(this) to your function such that:

$('element.selector').live("click", function (){
        run_some_func ($(this));
});

..and then

run_some_func(obj){
    obj.do_something();
})

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827406

You can use the call function to change the context (set the this keyword) on the function you want to execute:

$('element.selector').live("click", function (){
  run_some_func.call(this); // change the context of run_some_func
});

function run_some_func () {
  // the this keyword will be the element that triggered the event
}

And if you need to pass some arguments to that function, you can:

run_some_func.call(this, arg1, arg2, arg3); // call run_some_func(arg1,arg2,arg3)
                                            // and change the context (this)

Upvotes: 5

Related Questions