取消锚元素<li>中包含的mousedown事件(使用纯js)

Cancel mousedown event (with plain js) on anchor element wrapped in <li>

本文关键字:事件 js mousedown 包含 元素 li 取消      更新时间:2023-09-26

我有以下标记:

<ul>
 <li id="aCont">
  <a href="http://test.com">test</a>
 </li>
</ul>
<script type="text/javascript">
document.getElementById("aCont").onmousedown= function (e) {
 //some Action
}
<script>

我没有设法使它与e.preventDefault()e.stopPropagation()return false。有可能取消这个活动吗?

谢谢

假设你的目的是阻止锚点元素的点击导航到指定的URL,那么你需要使用"onclick"事件,而不是"onmousedown"。

对于旧式的element.onsomeevent =处理程序,只有非IE浏览器将事件对象作为参数传递给函数,而IE有window.event属性-因此您也需要允许。

并且,再一次,IE在阻止与事件相关的默认操作时做的事情不同:对于IE设置事件的returnValue属性为false,对于非IE调用e.preventDefault()(注意"防止"末尾的"t"-你在问题中拼写错误)和/或从处理程序返回false。

结合所有这些:

document.getElementById("aCont").onclick = function(e) {
   // allow for IE, which doesn't pass the event object as a parameter
   if (!e) e = window.event;
   e.returnValue = false;
   if (e.preventDefault)
      e.preventDefault();
   return false;
}

(注意:您也拼错了e.stopPropagation(),但您不需要该方法用于此目的-它会阻止事件冒气泡到父元素,它不会取消默认操作。)