开发者

Accessing properties of html element inside javascript function using $(this) gives undefined

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?


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.


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.


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.


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"));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜