2

说我有一个链接:

<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的情况下使这成为可能,因为我宁愿不

4

4 回答 4

4

用于return stopLight()处理onclick程序。
正如 mplungjan 在他的评论中所建议的那样

于 2012-12-14T16:07:08.880 回答
2

为了削减默认动​​作:

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
}​

干杯。

于 2012-12-14T16:09:56.223 回答
2

您可以使用 jQuery 和 event.preventDefault() 方法来做到这一点:

$('a.yourLink').on('click',function(e){
  if (stopLight()){ 
    e.preventDefault();
  }
});

如果 stopLight 为 true<a>将阻止默认行为,否则将正常执行

于 2012-12-14T16:09:56.287 回答
1

纯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;) 
  });
});
于 2012-12-14T16:13:23.323 回答