Evertjan.
2/19/2015 10:40:00 PM
JeffG <jeffgutsell@fuse.net> wrote on 19 feb 2015 in comp.lang.javascript:
> I am developing an HTML5 site and recently was surprised and puzzled by
> a problem I encountered when passing a "this" object to a function. I
> would like to understand what is happening here.
>
> I want to use the "this" object to get the parent element.
>
> This code works:
> HTML:
> <li><a href="#" onclick="MyFuc(this, 'anID');void(0);"> ...
> Script:
> function MyFunc(alink, anelem) {
> var ParElem = alink.parentNode;
> //...
>}
> This code does NOT work:
> HTML:
> <li><a href="javascript:MyFuc(this, 'anID');void(0);"> ...
>
> I've attempted to test what's different, and it seems that "this" is
> referencing something other than the "a" element.
The difference is, that "this" in onclick is defined,
while calling javascript in href is setting up a separate instance of JS
without DOM reference, so the latter "this" should not reference anything.
<a onclick='alert(this.innerHTML);'>x</a> alerts "x"
<a href='javascript:alert(this);return false;'>y</a> console error
> onclick="MyFuc(this, 'anID');void(0);"
better [imho] do:
onclick="MyFuc(this, 'anID');return false;"
if you want to prohibit the href from executing.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)