开发者

Get reference to anchor's dom element from javascript

开发者 https://www.devze.com 2023-01-17 09:10 出处:网络
If I have a some javascript in an anchor\'s href attribut开发者_JAVA技巧e: <a href=\"javascript:alert(\'hello!\')\">

If I have a some javascript in an anchor's href attribut开发者_JAVA技巧e:

<a href="javascript:alert('hello!')">

Is there a way I can get a reference to the DOM element that was clicked when the script executes? I mean, I know I could do

<a href="javascript:alert('hello from '+document.getElementById('thisAnchor'))" id="thisAnchor">

But I was hoping for something more like

<a href="javascript:alert('hello from '+target)">


Something like this?

Example: http://jsfiddle.net/TTzDb/

<a href="#" onclick="alert('hello from '+this.innerHTML)">me</a>​​​​​​​​​​​​​​

Using onclick, this will refer to the element that received the event.


Move the JavaScript to the onclick="yourJavaScriptHere" attribute. Then you can use the 'this' keyword to reference your anchor. So

<a href="#" onclick="alert('hello from '+this)">some text</a>

Although, that isn't very meaning. Additionally, it is a better practice to separate your JavaScript from your HTML to build a more maintainable website.


Yes, and the answer is this which refers to current DOM element:

<a href="javascript:alert('Hello from ' + this.tagName);">Click me</a>

EDIT:

Of course as bobince mentioned (see comments) that won't work as excepted. The correct form is:

<a href="..." onclick="alert('Hello from ' + this.tagName);">Click me</a>
0

精彩评论

暂无评论...
验证码 换一张
取 消