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

मुझे लगता है कि आपको एक 'href' की आवश्यकता है जो जावास्क्रिप्ट फ़ंक्शन कॉल नहीं है। यदि आप 'href =" # "' का उपयोग करते हैं तो यह काम करना चाहिए और आप स्क्रिप्ट निष्पादन के लिए 'onclick = "function ...' का उपयोग करते हैं। मुझे लगता है कि यह एक ऐसा है कि एंकर टैग उचित के बिना असली टैग नहीं है 'href'। – andyb

+0

obj के लिए' 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 = "जावास्क्रिप्ट: शून्य (0);" सुरक्षित है (कोई वापसी झूठी नहीं, कोई आधार यूआरएल हस्तक्षेप नहीं) – spraff

+0

इसके अलावा,' href = "जावास्क्रिप्ट : शून्य (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 वस्तु सभी ब्राउज़रों में एक ही नहीं संभाला है। यह कई वस्तुओं में से एक है जो प्रोटोटाइप और jQuery जैसी लाइब्रेरी सामान्य करने की कोशिश करते हैं। हालांकि, अधिकांश ब्राउज़रों ने onclick हैंडल (href के बजाय) के साथ उचित this पास कर दिया है, क्योंकि कई अन्य उत्तरों ने बताया है। यदि आप this उचित रूप से संभालना चाहते हैं, तो आपको this question में विस्तृत की तरह चीजें करने की आवश्यकता होगी।

संबंधित मुद्दे