return、reutrn false、e.preventDefault、e.stopPropagation、e.stopImmediatePropagation的简单使用

return

var i = function(){
            return
        }
        console.log(i())//undefined

return的主要作用是阻止函数继续执行,直接返回undefined

return false

<a class="baidu" href="http://www.baidu.com">百度</a>
$('.baidu').on('click',function(e){
            console.log(1)
           return false
        })//1

并未跳转页面,当每次调用return false时,实际做了3件事情

1.event.preventDefault();

2.event.stopPropagation();

3.停止回调函数执行并立即返回

e.preventDefault

$('.baidu').on('click',function(e){
            console.log(1)
           e.preventDefault()
        })//1

e.preventDefault()方法用来阻止浏览器继续执行默认行为,这里阻止了页面的跳转

e.stopPropagation

<div class="btn"><a class="baidu" href="http://www.baidu.com">百度</a></div>
$('.btn').on('click', function () {
        console.log(520)
    })
    $('.btn .baidu').on('click', function (e) {
        console.log(1)
        e.preventDefault()
        e.stopPropagation()
    })

输出结果为1

e.stopPropagation阻止事件冒泡

$('.btn .baidu').on('click',function(e){
        console.log(1)
        e.preventDefault()
    })
    $('.btn .baidu').on('click',function(e){
        console.log(2)
        e.preventDefault()
        e.stopImmediatePropagation()
    })
    $('.btn .baidu').on('click',function(e){
        e.preventDefault()
        console.log(3)
    })
    $('.btn').on('click',function(e){
        e.preventDefault()
        console.log(4)
    })

点击输出结果为1,2

e.stopImmediatePropagation()会停止一个事件继续执行,即使当前的对象上还绑定了其他处理函数,所有绑定在一个对象上的事件会按照绑定顺序执行

综上所述

return阻止函数继续执行,返回undefined

return false有三个作用,阻止浏览器默认行为,阻止事件冒泡,停止回调函数执行并立即返回

event.preventDefault阻止浏览器默认行为

event.stopPropagation阻止事件冒泡

event.stopImmediatePropagation停止一个事件继续执行




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值