欢迎来到电脑知识学习网,专业的电脑知识大全学习平台!

手机版

preventdefault作用(jQuery事件阻止冒泡stopPropagation)

网络知识 发布时间:2021-09-10 10:11:14

1、阻止默认行为

阻止<a>超链接的跳转href

<a onclick="testEvent(event)" href="baidu.com"></a>
function testEvent(event){
  event.preventDefault(); // 该方法阻止元素发生默认的行为
  window.zhad.push({eventtype: 'js_buy'});
  setTimeout(function(){
    window.location.href=event.target.href;
  }, 200); 
}
//或者
 $("a").click(function(e){
   e.preventDefault();
 });

阻止表单的提交

$("form:eq(0)").submit(function(e){
  e.preventDefault();
});

阻止鼠标右键(contextmenu表示鼠标右键事件):

$( document ).contextmenu(function(e) {
   e.preventDefault();
 });
//contextmenu表示鼠标右键事件,用法与一般事件相同
//等同于
$(document).bind("contextmenu",function(){
  alert("鼠标右键")
});

2、阻止冒泡并阻止默认行为

$("a").click(function(e){
  e.preventDefault();
  e.stopPropagation();//取消事件冒泡
});
//等效于
$("a").click(function(e){
  return false;
});

取消冒泡并阻止后续事件 stopImmediatePropatation()

$(":submit").click(function(e){
  e.stopImmediatePropagation();
  //e.stopPropagation();

  alert("1");
});

$(":submit").click(function(){
  alert("2");
});

//例子说明:如果使用stopPropagation()那么会取消冒泡,但是仍然后弹出两次。
//如果使用stopImmediatePropatation()那么不但会取消冒泡,还会取消后续绑定的事件。

3、取消默认回车事件

有时候回车按键的默认事件不是我们想要的,可以通过阻止事件的默认行为来达到我们想要的效果。

$(document).on('keydown', 'li', function(e) {
    if(e.keyCode == 13) {
        e.preventDefault()
    }
})
//等效于
$("li").keydown(function(e) {
    if(e.keyCode == 13) {
        e.preventDefault()
    }
})
责任编辑:电脑知识学习网

网络知识