简体   繁体   中英

I can't wrap jQuery object around anchor passed to its own onclick function


I have a link that looks this way:

<a href='#close' onclick='javascript:RequestClosure(this, event, 1012236);'>Request closure</a>

The RequestClosure function looks like this:

function RequestClosure(sender, e, partsID)
{
  alert($(sender).html());
}

When the function is executed it shows nothing, like $(sender) does not exist. But if I write something like this

function RequestClosure(sender, e, partsID)
{
  alert(sender);
  // or this
  alert(sender.href);
}

it works and shows href property

What am I doing wrong?

> <a href='#close' onclick='javascript:RequestClosure(this, event, 1012236);'>Request closure</a>

The javascript: in the onclick attribute vaule is treated as a label, do not use it.

> function RequestClosure(sender, e, partsID)

By convention, function names starting with a capital letter are reserved for constructors that should be called with new .

> {
>   alert($(sender).html());
> }

The last line would be much more efficient as:

alert(sender.innerHTML);

since that is what jQuery uses (it also removes the non-standard attributes it adds for event management).

When the function is executed it shows nothing, like $(sender) does not exist.

One of the joys of jQuery - when things go awry, it likes to silently fail.

Sorry guys,
The problem was that jQuery file was not correctly included. :(
That was so lame:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM