开发者

Calling JS functions from links in IE?

开发者 https://www.devze.com 2023-01-13 12:53 出处:网络
If I have a function like this: function foo() { //... return false; } I开发者_运维百科 can call it like this:

If I have a function like this:

function foo()
{
    //...
    return false;
}

I开发者_运维百科 can call it like this:

<a href="#" onClick="foo()">Run Foo</a>

However, in all browsers, this puts an # in the URL which I do not want.

So instead I do this:

<a href="javascript:foo()">Run Foo</a>

Which works fine in chrome but in IE it loads a page containing the string false.

Whats the best practice here?


You don't need the javascript: protocol.

<a href="#" onclick="foo(); return false">Run Foo</a>

is all you need.


Like @wrumbsy says...

You don't need the javascript: protocol.

<a href="#" onclick="foo(); return false">Run Foo</a>

... but this means you don't need an anchor <a> either. Only use anchors for hyperlinks; not for JS-enhanced interactivity.

A span will work just as well, with cursor:pointer; CSS property:

<span style="cursor:pointer;" onclick="foo(); return false">Run Foo</span>
0

精彩评论

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