2012-02-16 11 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

'console.log(e.tagName);を使用すると、 – mgraph

+0

JavaScript関数呼び出しではないhrefが必要だと思います。スクリプト実行のために 'href ="# "'を使用し、 'onclick =" function ... "を使用するとうまくいくはずです。アンカータグが実際のタグでないかどうか'href'。 – andyb

+0

オブジェクトに' e'を使用しないでください。 'e'はイベントオブジェクトの標準です – gdoron

答えて

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

href = "javascript:void(0);"はより安全です(falseを返さず、ベースURLの干渉がありません)。 – spraff

+0

また、 'href =" javascript :void(0); "は、リンク上をクリックすると直ちにブラウザのビューポートをドキュメントの先頭にジャンプさせないので、' href = "#" 'よりも優れています。 – Abdull

4

You can do this directly too

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

私はタグ名を必要としません、デモンストレーションの目的のためだけです、私は要素が必要です – spraff

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

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

それは、イベントオブジェクトのための標準ですe要素を呼び出さないでください。

JSfiddle DEMO

0

thisオブジェクトはすべてのブラウザで同じように処理されていません。これは、PrototypeやjQueryのようなライブラリが正規化しようとする多くのアイテムの1つです。しかし、多くのブラウザで指摘されているように、onclickハンドル(hrefではなく)の間に、ほとんどのブラウザで適切なthisが渡されます。 thisを適切に処理したい場合は、this questionのような処理を行う必要があります。

関連する問題