取消包裹在< li>中的锚元素上的mousedown事件(使用纯js).
我有以下标记:
<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
都无法实现.可以取消这个活动吗?
I didn't manage to make it with e.preventDefault()
and e.stopPropagation()
neither with return false
. Is it possible to be canceled this event at all?
谢谢
假设您的意图是阻止对锚元素的单击导航到指定的URL,那么您需要使用"onclick"事件,而不是"onmousedown"事件.
Assuming your intention is to stop the click on the anchor element from navigating to the specified URL then you need to be using the "onclick" event, not "onmousedown".
使用老式的 element.onsomeevent =
处理程序,只有非IE浏览器将事件对象作为参数传递给函数,而IE具有 window.event
属性-因此您也需要考虑到这一点.
With an old-school element.onsomeevent =
handler only non-IE browsers pass the event object to the function as a parameter, while IE has a window.event
property - so you need to allow for that too.
同样,当阻止与事件关联的默认操作时,IE也会做不同的事情:对于IE,将事件的 returnValue
属性设置为false,对于非IE调用 e.preventDefault()
(请注意"prevent"末尾的"t"-您在问题中拼写错误)和/或从处理程序中返回false.
And, again, IE does things differently when preventing the default action associated with events: for IE set the event's returnValue
property to false, for non-IE call e.preventDefault()
(note the "t" on the end of "prevent" - you've spelled it wrong in your question) and/or return false from the handler.
结合所有这些:
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()
错误,但您不需要该方法来实现此目的-它可以阻止事件冒泡到父元素,它不会这样做.t取消默认操作.)
(Note: you've also spelled e.stopPropagation()
wrong, but you don't need that method for this purpose - it stops the event bubbling up to parent elements, it doesn't cancel the default action.)