Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #26874

Re: using 'this' to reference an 'a' element

Newsgroups comp.lang.javascript
Subject Re: using 'this' to reference an 'a' element
From "Evertjan." <exxjxw.hannivoort@inter.nl.net>
References <7d66ec0e-ee46-49d2-9f65-4c1c185c1bd5@googlegroups.com>
Date 2015-02-19 23:40 +0100
Message-ID <XnsA446F0CCD9143eejj99@194.109.133.133> (permalink)

Show all headers | View raw


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)

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

using 'this' to reference an 'a' element JeffG <jeffgutsell@fuse.net> - 2015-02-19 14:20 -0800
  Re: using 'this' to reference an 'a' element "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2015-02-19 23:40 +0100
  Re: using 'this' to reference an 'a' element JeffG <jeffgutsell@fuse.net> - 2015-02-23 11:12 -0800
    Re: using 'this' to reference an 'a' element "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2015-02-23 21:59 +0100

csiph-web