文本区域的变化与延迟

Textarea on change with delay

本文关键字:延迟 变化 区域 文本      更新时间:2023-09-26

我想用扫描仪扫描qr码。我已经有了一个扫描仪,当我把焦点放在一个隐藏的文本区域时,当我扫描qr码时,他会把文本放在文本区域。

我想对特定文本区域中输出的数据做一些事情。现在我在jQuery中有如下内容:

$("#qr_data").bind("input", function (e) {
    console.log(e);
});

问题是,在我的文本区qr数据的加载需要2秒左右。这个函数被调用了20次... .我只想要最后的数据,这样我才能对它做点什么。我怎么能这么做?

嗨,我要做的是绑定到更改事件,并在每次触发时延迟函数500ms。就像你正在创建一个自动完成输入字段,你不想在每次击键时触发ajax请求。

var qr_timeout = null;
$("#qr_data").change(function(){
    if(qr_timeout != null)
        clearTimeout(qr_timeout);
    qr_timeout = setTimeout(function(){
         //Do your magic here 
    }, 500);
});

这样你就不用担心加载会花费1,2甚至10秒

// we will build a new event
// once for initing a new event "lastchange"
$("textarea").each(function () {
    var timer = null;
    $(this).change(function(){
        var node = this;
        if(timer != null)
            clearTimeout(timer);
        timer = setTimeout(function(){
             $(node).trigger('lastchange');
        }, 1000);
    });
});

// use custom event
$("textarea#qr_data").bind("lastchange", function (e) {
    console.log($(this).val(), e);
});