简体   繁体   English

使用 onclick 制作可点击的链接但没有 href=#?

[英]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) {}大约一百个,比如“cat1”、“cat2”、“dog1”、“dog2”、“dog3”等。然后我有一个function IDClick(id) {}

I need those identifiers clickable in HTML, to achieve that I used <a> tag with onclick我需要那些可在 HTML 中单击的标识符,以实现我在onclick使用<a>标签

<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=#所以我尝试添加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.现在光标正常了,但是当我单击该项目时,浏览器位置栏中的 URL 会发生变化。 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)".引用上面@aij 的评论:“使用 CSS 使它看起来不错,但仍然无法从键盘访问它(即,选项卡永远不会聚焦链接)”。

You can use CSS to force the cursor to change on hover of the clickable element:您可以使用 CSS 强制光标在可点击元素悬停时改变:

.myClickableThingy {
    cursor: pointer;
}

And then you can switch back to <span> s or whatever of element you were using before <a> tags.然后您可以切换回<span> s 或您在<a>标签之前使用的任何元素。

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:还有你的 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;使用return false; in the IDClick handler function.在 IDClick 处理函数中。

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

IDClick() {

   ...
   return false;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM