简体   繁体   中英

function in HREF not working using javascript

I have function which needs to be run on click event. However it is working fine with onclick attribute of anchor tag but not working with HREF attribute. It is giving id undefined. Here is demo code

HTML

<a href="javascript:test(this)" id="first">click</a>

JS

function test(obj){
alert(obj.id)
}

this in that context is the window , not the control. Placing javascript in the href is not the same as an event handler like onclick . Here's a fiddle .

这是一个修复:

<a href="#" onclick="javascript:test(this);" id="first">click</a>

This question already got answers but if you want to use a function as you used in your question then you should use it like

HTML:

<a href="http://heera.it" onclick="return test(this.id)" id="first">click</a>

JS:

function test(obj){
    alert(obj);
    return false; // this is required to stop navigation to that link
}

notice, return false , if you have value in href like this example, then you should use return false but there are other options like event.preventDefault() or event.returnValue = false (for IE) for this reason.

DEMO. Another DEMO (without return false ). Read about this keyword on MDN.

I enjoyed Matt Kruse's Javascript Best Practices article. In it, he states that using the href section to execute JavaScript code is a bad idea.

here are some good practices to call javascript on anchor:

<a href="javascript:;" onClick="return DoSomething();">link</a>
<a href="javascript:void(0);" onClick="return DoSomething();">link</a>
<a href="#" onClick="return DoSomething();">link</a>

Use onclick event of the anchor tag. this inside href represents current window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM