2012-02-16 6 views
20

I expect this to print "a" because when I call foo(this), the argument seems to be the link tag.<a href="javascript:foo(this)"> passes Window, I want the tag element itself

<script type="text/javascript"> 
    function foo (e) { 
     alert (e .tagName); 
    } 
</script> 
<a href="javascript:foo(this)">click</a> 

Instead, it prints "undefined". If I alert(e) it says "object Window". How do I make foo know which element launched it? Without passing/looking up ids.

+0

cosa succede se si utilizza 'console.log (e.tagName);' – mgraph

+0

Penso che sia necessario un 'href' che non sia la chiamata della funzione JavaScript. Dovrebbe funzionare se usi 'href =" # "' e usi 'onclick =" function ... 'per l'esecuzione dello script. Penso che sia qualcosa a che fare con il modo in cui un anchor tag non è un vero tag senza un vero e proprio 'href'. – andyb

+0

Non utilizzare' e' per l'oggetto. 'e' è uno standard per l'oggetto evento – gdoron

risposta

29

You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.

<a href="#" onclick="foo(this)">click</a> 

You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.

It is better to attach the event with Unobtrusive JavaScript

+4

Se "Sarò pignolo per la filosofia del codice, suppongo che valga la pena sottolineare che" href = "javascript: void (0);" "è più sicuro (nessun ritorno falso, nessuna interferenza url di base). – spraff

+0

Inoltre," href = "javascript : void (0); "' è migliore di 'href =" # "' perché non fa in modo che la finestra del browser salti all'inizio del documento non appena si fa clic sul collegamento. – Abdull

4

You can do this directly too

<a href="#" onclick="alert(this.tagName);">click</a>​ 
+0

Non voglio il nome del tag, che è solo a scopo dimostrativo, Voglio l'elemento. – spraff

0
<a href="#" onclick="foo(this)">click</a> 

function foo(obj) { 
    alert(obj.tagName); 
}​ 

Non chiamare l'elemento e è uno standard per l'oggetto evento.

JSfiddle DEMO

0

L'oggetto this non viene gestito lo stesso in tutti i browser. Questo è uno dei tanti elementi che le librerie come Prototype e jQuery cercano di normalizzare. Detto questo, tuttavia, la maggior parte dei browser passerà l'appropriato this durante l'handle onclick (anziché lo href) come hanno indicato molte altre risposte. Se si desidera gestire in modo appropriato lo this, sarà necessario eseguire operazioni come quelle dettagliate in this question.

Problemi correlati