如何禁用带有 javascript 和 css 的链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18450458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I disable a link with javascript and css?
提问by Tigran
Do you know how to disable link for user only? I have
您知道如何仅为用户禁用链接吗?我有
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')"><a href="./search/Banana">Banana</a></div>
So idea is that link /search/Banana is a valid link and I want to keep it for search indexing engines. However, I want when user click on link, the function searchoffertext_selected was called and nothing more happened.
所以想法是链接 /search/Banana 是一个有效链接,我想保留它以供搜索索引引擎使用。但是,我希望当用户点击链接时,函数 searchoffertext_selected 被调用并且没有发生更多的事情。
回答by AJ W
To stop the link from taking its default action add return false;
to the onclick
event:
要阻止链接执行其默认操作,请添加return false;
到onclick
事件中:
<div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;"><a href="./search/Banana">Banana</a></div>
It's probably a better idea to put the onclick
directly on the <a>
将onclick
直接放在<a>
But an even better approach would be to use unobtrusive JavaScriptto attach an event to the link via a selector.
但更好的方法是使用不显眼的 JavaScript通过选择器将事件附加到链接。
回答by Mohamad
Using jQuery:
使用jQuery:
$('#selector').click(function(e){
e.preventDefault();
});
VanilaJS:
香草JS:
<a onclick="return false;">
回答by Ozzy
Try this?
试试这个?
js
js
document.querySelectorAll('.searchoffertext > a').onclick = function(e) {
e.preventDefault();
searchoffertext_selected(this.getAttribute("data-fruit"));
}
html
html
<div class="searchoffertext">
<a href="./search/Banana" data-fruit="Banana">Banana</a>
</div>
回答by rink.attendant.6
HTML
HTML
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">
<a href="./search/Banana">Banana</a>
</div>
CSS
CSS
Use pointer-events
, but this is unsupported in versions of IE older than 11.
使用pointer-events
,但在 11 之前的 IE 版本中不受支持。
.searchoffertext > a {
pointer-events: none;
}
JavaScript
JavaScript
Prevent the default actionfrom executing when the link is clicked:
var links = document.querySelectorAll('.searchoffertext > a'), i;
for(i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function(e) {
e.preventDefault();
}, false);
}