Prevent a link from opening the URL:
document.getElementById("myAnchor").addEventListener("click", function(event){
event.preventDefault()
});
Try it Yourself »
More "Try it Yourself" examples below.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.
Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
preventDefault() | Yes | 9.0 | Yes | Yes | Yes |
event.preventDefault()
None |
Return Value: | No return value |
---|---|
DOM Version: | DOM Level 2 Events |
Prevent the default action of a checkbox:
document.getElementById("myCheckbox").addEventListener("click", function(event){
event.preventDefault()
});
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!