[英]How to block an html link without changing href?
說我有一個鏈接:
<a href="http://www.example.com">Example!</a>
我想保持鏈接完整,但我想要一個onclick事件來決定鏈接是否可點擊
<a onclick='stopLight()' href="http://www.example.com">Example!</a>
function stopLight() {
// conditional logic
// return true or return false
}
所以如果stopLight()== true,那么鏈接工作,如果stopLight()== false,則鏈接不起作用。 在不改變href的情況下實現這一點,因為我寧願不這樣做
對onclick
處理程序使用return stopLight()
。
正如mplungjan在他的評論中所說的那樣
為了削減默認動作:
stopLight = function (e) {
window.event.preventDefault();
}
這樣可以防止事件發生。
所以你可以這樣做:
<a onclick='isStopLight()' href="http://www.example.com">Example!</a>
在JS中
isStopLight= function(){
if(stopLight()){
window.event.preventDefault();
}
}
stopLight = function () {
// conditional logic
// return true or return false
}
干杯。
您可以使用jQuery和event.preventDefault()方法執行此操作:
$('a.yourLink').on('click',function(e){
if (stopLight()){
e.preventDefault();
}
});
如果stopLight為true,則將阻止<a>
的默認行為,否則執行正常
簡單的JS
<a onclick='return stopLight()' href="http://www.example.com">Example!</a>
window.onload=function() {
document.getElementById("stoplight").onclick=function() {
// conditional logic
// return true or return false
}
}
<a id="stoplight" href="http://www.example.com">Example!</a>
jQuery的
<a id="stoplight" href="http://www.example.com">Example!</a>
$(function() {
$("#stoplight").on("click",function(e) {
// conditional logic
if (false condition) e.preventDefault(); // (or return false;)
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.