views:

66

answers:

5

How can I pass the $this (the self keyword) to a function in Jquery

$(document).ready(function()
    {
        $('.nav a').click(function()    {
            var direction = $(this).attr("name");
            submit_form($(this))
        }); 

        function submit_form(this)
        {
            // do some stuff with 'this'


        }       

    });
A: 

Try this:

$(document).ready(function() 
    { 
        $('.nav a').click(function()    { 
            var direction = $(this).attr("name"); 
            submit_form(this);
        });  

        function submit_form(myObject) 
        { 
            // do some stuff with 'myObject'


        }        

    }); 
Fosco
+1  A: 

Wrapping it in $() makes it a jQuery object. You would want to do something like

submit_form(this);

function submit_form(obj)
{
    // Work with `obj` as "this"
    // Or wrap it in $() to work with it as jQuery(this)
}
Josh K
$(important point!)
TMP file guy
A: 

Just pass it as a normal variable?

function submit_form(context)
{
    context.html("Boo!");

}

/// Then when you call it:
submit_form($(this));
Aren
+1  A: 
ebynum
A: 

Here is what worked for me.

$(document).ready(function()
{
    $('.nav a').click(function()    {
        submit_form(this)
    }); 

    function submit_form(thisObject)
    {
        var direction = $(thisObject).attr("name");
    }       
});
TMP file guy
This is not a forum. Updates to your question should be made as an edit to your original question, not as an answer.
Justin Johnson