簡體   English   中英

如何在不更改href的情況下阻止html鏈接?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM