简体   繁体   中英

How to call JavaScript function instead of href in HTML

I have some mockup in HTML

<a href="javascript:ShowOld(2367,146986,2)"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

I got the response from server when I sent the request.

With this mockup I got as a response of AJAX request that sends my code to server.

Well, everything is fine but when I click on the link the browser wants to open the function as link; meaning after click I see the address bar as

javascript:ShowOld(2367,146986,2)

means browser thing that's url if I want to do this in firebug that's work. Now I want to do that then when anyone clicks the link then the browser tries to call the function already loaded in the DOM instead of trying to open them in browser.

That syntax should work OK, but you can try this alternative.

<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">

or

<a href="javascript:ShowOld(2367, 146986, 2);">

UPDATED ANSWER FOR STRING VALUES

If you are passing strings, use single quotes for your function's parameters

<a href="javascript:ShowOld('foo', 146986, 'bar');">

If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.

Eg:

<button onclick="ShowOld(2367,146986,2)">
    <img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>

Try to make your javascript unobtrusive :

  • you should use a real link in href attribute
  • and add a listener on click event to handle ajax

I use a little CSS on a span to make it look like a link like so:

CSS:

.link {
    color:blue;
    text-decoration:underline;
    cursor:pointer;
}

HTML:

<span class="link" onclick="javascript:showWindow('url');">Click Me</span>

JAVASCRIPT:

function showWindow(url) {
    window.open(url, "_blank", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}

<a href="#" onclick="javascript:ShowOld(2367,146986,2)">

Your should also separate the javascript from the HTML.
HTML:

<a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

javascript:

myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);

Just make sure the last line in the ShowOld function is:

return false;

as this will stop the link from opening in the browser.

href is optional for a elements.

It's completely sufficient to use

<a onclick="ShowOld(2367,146986,2)">link text</a>

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