javascript Jquery / JS 将“粘贴”事件处理程序绑定到输入文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5278808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:37:22  来源:igfitidea点击:

Jquery / JS bind "paste" event handler to input textbox

javascriptjqueryevent-handlingmouseeventpaste

提问by Ave

Allright, SO i have an input box and I need to do things everytime it changes, I am having trouble doing it for mouse paste. Here is the code I have

好吧,所以我有一个输入框,每次更改时我都需要做一些事情,我在鼠标粘贴时遇到了麻烦。这是我的代码

$("#attack-navy"+unit.ID+"-number").bind('paste', function(){
            alert("paste detected");
            $("#attack-max-capacity").text(getMaxCapacity());
});

the getMaxCapacity() function return number entered * 30 for now;

getMaxCapacity() 函数现在返回输入的数字 * 30;

Here is the scenario when
1: I paste 3, it will not change (i still see the alert)
2: Then when i paste 5, it will be 90(3 * 30)
3: Then if i paste 10 it will be 150(5 * 30), and so on.

这是
1的情况 :我粘贴 3,它不会改变(我仍然看到警报)
2:然后当我粘贴 5 时,它将是 90(3 * 30)
3:然后如果我粘贴 10,它将是 150 (5 * 30) 等等。

I think its doing the handler before the paste actually occurs. Any ideas on what I can do? (.change will not work, it must happen as soon as u paste)

我认为它在粘贴实际发生之前执行处理程序。关于我能做什么的任何想法?(.change 不起作用,它必须在你粘贴后立即发生)

回答by SLaks

You should handle the inputand propertychangeevents.
Demo.

您应该处理inputpropertychange事件。
演示

回答by tilleryj

You're right. The paste event is firing before the value of the input changes. Try wrapping your handler in a timeout:

你说得对。粘贴事件在输入值更改之前触发。尝试在超时中包装您的处理程序:

setTimeout(function() { $("#attack-max-capacity").text(getMaxCapacity()); }, 0);

回答by karev

Replace the bind event with .live and it should work, like this:

用 .live 替换绑定事件,它应该可以工作,如下所示:

$("#attack-navy"+unit.ID+"-number").live('paste', function(){
            alert("paste detected");
            $("#attack-max-capacity").text(getMaxCapacity());
});