阻止默认动作或事件冒泡

如何取消事件或防止事件冒泡DOM树


jQuery提供了两个有用的方法,可以在事件处理程序中调用它们,以阻止事件发生:e.preventDefault()e.stopPropagation()

实际上,这两种都是JavaScript原生支持的方法,可在任何处理程序函数的事件对象上使用:


function handler(e) {
    // stop the immediate action of this event
    e.preventDefault();

    // prevent the event fro bubbling up
    e.stopPropagation();
}

// attach handler to the keydown event of the document
if (document.attachEvent) document.attachEvent('onkeydown', handler);
else document.addEventListener('keydown', handler);
      

从事件处理程序返回false在大多数情况下与调用这些方法具有相同的效果,但是也有例外,例如表单提交(提交事件)。