Thursday, October 30, 2008

[jQuery] Re: $(this) question

In the addSubject function the "this" will point to "window" object. That means the function is in the global scope. If you want to pass the element to addSubject function do like this

Use html like this
<a href="#" onclick="addSubject(this);">add</a>
  Here "this" keyword can only be used in event handlers not on normal HTML attributes like href.

Use js like this
function addSubject(ele) {
       alert( $(ele).attr("href") );
}

If you still want your ouput should be "javascript:addSubject();" Then change the html to
<a href="javascript:addSubject();" onclick="addSubject(this); return false;">add</a>



On Thu, Oct 30, 2008 at 4:20 PM, Thomas <Tom.Roncsak@gmail.com> wrote:

Hi!

I have this in html:
<a href="javascript:addSubject();">add</a>

and this in js:
function addSubject() {
       alert( $(this).attr("href") );
}
/* expected output:
 *
 *javascript:addSubject();
 *
 */

I tried some alternate method but those not works neither... What is
the problem ?

Thomas

No comments: