如何在 HTML 中调用 JavaScript 函数而不是 href

我有一些 HTML 的样机

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

我发送请求时收到了服务器的响应。

通过这个样机,我得到了一个 AJAX 请求的响应,它将我的代码发送到服务器。

嗯,一切都很好,但当我点击链接时,浏览器希望打开的功能作为链接; 这意味着在点击后,我看到的地址栏为

javascript:ShowOld(2367,146986,2)

意味着浏览器的事情,这是网址,如果我想这样做,在 Firebug,这是工作。现在我想这样做,然后当任何人点击链接,然后浏览器尝试调用已经加载在 DOM 中的函数,而不是尝试在浏览器中打开它们。

435294 次浏览

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');">

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

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

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.

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

E.g.:

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

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");
}

href is optional for a elements.

It's completely sufficient to use

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