views:

50

answers:

4

I am calling a function test() on an anchor tag like this:-

<a class="link" onclick="test();">Hello</a>

And I am trying to access the class of the anchor inside the function test():-

function test()
{
  alert($(this).attr("class"));
}

But this alerts undefined. I know that calling onclick=test(this); instead and having the following function works:-

function test(obj)
{
  alert($(obj).attr("class"));
}

But, I wanted to access the properties of the element (on which the function is called) without passing a this. Just be able to get/set properties of the element (on which the function is called). Is it possible? How to do this?

Thanks,
Sandeepan

A: 

Because "this" is a special free variable in Javascript: it is bound by the context of the caller. Passing this is a better and safer way of doing the job.

daitangio
+3  A: 

this is "The object on which this function was called", so for foo.test(), this is foo inside test. If you don't specify an object, it defaults to window so in your code this === window since you are calling (implicitly) window.test().

Forget about intrinsic event attributes. They are ugly and do not lend themselves to unobtrusive JavaScript.

Instead, use JavaScript to assign your event handlers. jQuery, which you are already using, provides a number of ways to do this, including click. Pass the function you want to call as the argument to it.

jQuery('.link').click(test);

When the click event fires, it will now call something akin to HTMLElementNode.test() instead of HTMLElementNode.onclick() so this will be what you want.

David Dorward
Sorry I did not understand. Can you explain a little...
sandeepan
Ok +1 now it is more clear...
sandeepan
+2  A: 

In this scenario we need to make sure that HTML element owns that function which you wanna call upon click. What u actually doing is that u are using onclick attribute which just takes string parameter and completely oblivious of everything else.

In order to make HTML element owner of the function you need to map onclick property completely with your own custom function. In JavaScript you do that like that

element.onclick = doSomething;

So our code will be something like

<div id="element">Click</div>
<script>
function doSomething(){
    this.style.color= "#000000"
}
document.getElementById("element").onclick = doSomething;
</script>

here is the working example http://www.jsfiddle.net/VMCmb/1/.

Also please take a look at http://www.quirksmode.org/js/this.html.

Ayaz Alavi
Simpler answer and nice links... Thanks
sandeepan
A: 

You could also use this method -

Pass this as a parameter -

<a class="link" onclick="test(this);">Hello</a>

Jquery code will be -

function test(obj)
{
  alert($(obj).attr("class"));
}
Alpesh