js 防抖传参并绑定this

引言

网上有不少防抖代码是内含传参功能的,但是没有具体的传参使用实例,希望我的案例能帮到大家。


实例:输入同时显示,防抖延迟显示


无传参版

在这里插入图片描述
HTML

<div>
    <input id="input" type="text">
    <p id="content"></p>
</div>

JS

    let input = document.getElementById('input');
    let content = document.getElementById('content');

    input.onkeyup=debounce(show,1000);

    function show() {
        content.innerHTML+=this.value+'<br/>';
    }

    function debounce(func,delay) {
        let timer;
        return function () {
            if(timer)
                clearTimeout(timer);
            timer= setTimeout(()=>{
                func.call(this);
            },delay);
        }
    }

传参版

在这里插入图片描述

    let input = document.getElementById('input');
    let content = document.getElementById('content');

	//将this绑定到input上,并传递参数
    input.onkeyup=debounce(show,1000).bind(input,',hello',',world');

    function show(arg1,arg2) {
        content.innerHTML+=this.value+arg1+arg2+'<br/>';
    }

    function debounce(func,delay) {
        let timer;
        return function () {
            if(timer)
                clearTimeout(timer);
            timer= setTimeout(()=>{
                func.call(this,...arguments);
            },delay);
        }
    }

注意坑(下面写法都无效)!!!

//无效,onkeyup需要赋值一个函数,而该写法为立即执行。
input.onkeyup=debounce(show,1000)(',hello',',world');

//无效,会丢失指向input的this,show函数内获取不到input的值。
input.onkeyup=function() {
	debounce(show, 1000)(',hello',',world');
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值