HTML:onclick 优先于 href

发布于 2024-10-05 16:03:46 字数 116 浏览 0 评论 0原文

我想知道是否可以在 html 标签上同时使用 onclick 和 href 并优先考虑 onclick 而不是 href。 我只想获得 robots/oldbrowsers 可访问性的 href。

谢谢

I would like to know if it's possible to have both onclick and href on a html tag and priorize the onclick over the href.
I just want to have a href for robots/oldbrowsers accessibility.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

亚希 2024-10-12 16:03:46

是的,只需从 onclick 处理程序返回 false,它将阻止默认操作,即浏览器打开 href 中的链接。

Yes, just return false from the onclick handler and it will prevent the default action which is that the browser is opening the link in the href.

滴情不沾 2024-10-12 16:03:46

如果您希望 JavaScript 不引人注目,则可以使用 addEventListener 而不是使用链接的 onclick 属性来绑定事件。

添加事件侦听器时,您可以定义一个 event 参数,该参数具有抑制元素默认行为的方法。在这种情况下,它将阻止浏览器导航到链接的 href

myLink.addEventListener("click", function(event) {
    event.preventDefault();
    /* onclick logic goes here */ 
}, false);

或者在 jQuery 中。 。 。

jQuery('#myLink').click(function(event){
    event.preventDefault();
    /* onclick logic goes here */ 
});

If you want your JavaScript to be unobtrusive, you can bind your events by using addEventListener instead of using the onclick property of the link.

When you add an event listener you can define an event parameter which has a method to suppress the default behavior of the element. In this case, it will stop the browser from navigating to the href of the link.

myLink.addEventListener("click", function(event) {
    event.preventDefault();
    /* onclick logic goes here */ 
}, false);

or in jQuery . . .

jQuery('#myLink').click(function(event){
    event.preventDefault();
    /* onclick logic goes here */ 
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文