I have links like this:
<a href="#" onclick="myfunc({a:1, b:'hi'})" />click</a>
<a href="#" onclick="myfunc({a:3, b:'jo'})" />click</a>
And I would like to do a preventDefault()
inside myfunc()
, because a #
will be added in the address bar when clicking on the link (without doing return false;
or href='javascript:void(0);'
)
Is this possible? Can I get the event inside myfunc()
ベストアンサー1
I believe you can pass in event
into the function inline which will be the event
object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event
).
function sayHi(e) {
e.preventDefault();
alert("hi");
}
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>
- Run it as is and notice that the link does no redirect to Google after the alert.
- Then, change the
event
passed into theonclick
handler to something else likee
, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).