Textarea 延迟改变事件

3
我希望能够使用扫描器扫描QR码。我已经有了一个扫描器,当我将焦点放在隐藏的文本区域中时,他会在我扫描QR码时将文本放入文本区域。
我想对特定文本区域输出的数据进行处理。现在我的jQuery代码如下:
$("#qr_data").bind("input", function (e) {
    console.log(e);
});

问题是我的文本区域中QR数据的加载大概需要2秒钟左右。所以这个函数被调用了20次……我只想要最后一个数据,这样我才能对其进行操作。我该如何做到这一点?

你能否使用 change 事件并添加延迟(timeout)?请参考之前的答案:https://dev59.com/AGox5IYBdhLWcg3wHAwA - Pete
2个回答

3

你可以绑定到change事件,并且每次事件触发后延迟500毫秒执行函数。比如你正在制作一个自动完成输入框,而你又不想在每次按键时都发送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秒的时间。

2
// 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);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接