简体   繁体   中英

Make a clickable link with onclick but without href=#?

I have a set of clickable identifiers on my page. About hundred, like 'cat1', 'cat2', 'dog1', 'dog2', 'dog3' etc. Then I have a function IDClick(id) {}

I need those identifiers clickable in HTML, to achieve that I used <a> tag with onclick

<a onclick=IDClick(id)>id</a>

now it works, but the cursor will not change when it is hovered over the clickable element.

So I try to add href=#

<a href=# onclick=IDClick(id)>id</a>

Now the cursor is OK, but when I click the item, the URL in the browser location bar will change. This is not desired.

How to get the mixed behavior?

I do not need underline as well.

You need to stop the browser from doing it's default action.

<a href="#" onclick="IDClick(id);event.preventDefault();">id</a>

When you click on a link, the default action is to go to that address. event.preventDefault(); prevents the browser from doing the default action.

This is a significantly better solution for accessibility. Quoting @aij's comment above : "using CSS makes it look ok, but still leaves it inaccessible from the keyboard (ie, tab will never focus the link)".

You can use CSS to force the cursor to change on hover of the clickable element:

.myClickableThingy {
    cursor: pointer;
}

And then you can switch back to <span> s or whatever of element you were using before <a> tags.

Give your anchor element a class and style it to achieve what you need:

<a class='kinda-link' onclick='whatevs()'>Hi I'm a kinda-link</a>

And your css:

a.kinda-link:hover { cursor: pointer; }

Recently I use clickable spans in most cases.

 Some text with some <span onclick="alert('hey there')" style="color: blue; cursor: pointer">part</span> that is clickable.

Use return false; in the IDClick handler function.

<a href=# onclick=IDClick(id)>id</a>

IDClick() {

   ...
   return false;

}

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