Javascript jQuery 可以检查输入的内容是否发生了变化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7534890/
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
Can jQuery check whether input content has changed?
提问by Pavel S.
Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
是否有可能以某种方式将 javascript(jQuery 是最好的)事件绑定到“更改”表单输入值?
I know about .change()
method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup()
method but it reacts also on arrow keys and so on.
我知道.change()
方法,但它不会触发,直到您(光标)离开输入字段。我也考虑过使用.keyup()
方法,但它也会对箭头键等做出反应。
I need just trigger an action every timethe text in the input changes, even if it's only one letter change.
每次输入中的文本更改时,我只需要触发一个操作,即使只是一个字母更改。
回答by Tim Down
There is a simple solution, which is the HTML5 input
event. It's supported in current versions of all major browsers for <input type="text">
elements and there's a simple workaround for IE < 9. See the following answers for more details:
有一个简单的解决方案,那就是 HTML5input
事件。<input type="text">
元素的所有主要浏览器的当前版本都支持它,并且对于 IE < 9 有一个简单的解决方法。有关更多详细信息,请参阅以下答案:
Example (except IE < 9: see links above for workaround):
示例(IE < 9 除外:有关解决方法,请参见上面的链接):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
回答by alexn
Yes, compare it to the value it was before it changed.
是的,将其与更改之前的值进行比较。
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode
to figure out what key was pressed.
另一种选择是仅在某些键上触发更改的功能。使用e.KeyCode
弄清楚按下了哪个键。
回答by Rafay
function checkChange($this){
var value = $this.val();
var sv=$this.data("stored");
if(value!=sv)
$this.trigger("simpleChange");
}
$(document).ready(function(){
$(this).data("stored",$(this).val());
$("input").bind("keyup",function(e){
checkChange($(this));
});
$("input").bind("simpleChange",function(e){
alert("the value is chaneged");
});
});
here is the fiddle http://jsfiddle.net/Q9PqT/1/
回答by Kwaw Annor
You can also store the initial value in a data attribute and test it with the current value.
您还可以将初始值存储在数据属性中并使用当前值对其进行测试。
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
如果初始值未更改,则返回 true。
回答by jwatts1980
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
您可以在 jQuery 中使用数据并捕获所有事件,然后根据它的最后一个值(未经测试)对其进行测试:
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data
means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc")
to track many fields.
这对于一长串项目也很有效。使用jQuery.data
意味着您不必创建 javascript 变量来跟踪值。您可以$("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc")
跟踪许多字段。
UPDATE: Added blur
to the bind
list.
更新:添加blur
到bind
列表中。
回答by mplungjan
I had to use this kind of code for a scanner that pasted stuff into the field
我不得不将这种代码用于将东西粘贴到现场的扫描仪
$(document).ready(function() {
var tId,oldVal;
$("#fieldId").focus(function() {
oldVal = $("#fieldId").val();
tId=setInterval(function() {
var newVal = $("#fieldId").val();
if (oldVal!=newVal) oldVal=newVal;
someaction() },100);
});
$("#fieldId").blur(function(){ clearInterval(tId)});
});
Not tested...
未测试...
回答by Sarel Botha
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
我认为没有“简单”的解决方案。您可能需要同时使用 onKeyUp 和 onChange 事件,以便在使用鼠标进行更改时也能捕捉到。每次调用您的代码时,您都可以将您“看到”的值存储在附加到该字段的 this.seenValue 上。这应该会更容易一些。
回答by GolezTrol
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
您可以在键和鼠标事件的组合上设置事件,当然也可以设置 onblur。在这种情况下,存储输入的值。在下一次调用中,将当前值与最后存储的值进行比较。只有在它确实发生变化时才施展魔法。
To do this in a more or less clean way:
要以或多或少干净的方式执行此操作:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
您可以将数据与 DOM 元素(查找 api.jquery.com/jQuery.data )相关联,因此您可以编写一组通用的事件处理程序,这些处理程序分配给表单中的所有元素。每个事件都可以将触发它的元素传递给一个通用函数。该函数可以将旧值添加到元素的数据中。这样,您应该能够将其实现为适用于整个表单以及您从现在开始编写的每个表单的通用代码。:) 而且我猜大概不会超过 20 行代码。
An example is in this fiddle: http://jsfiddle.net/zeEwX/
这个小提琴中有一个例子:http: //jsfiddle.net/zeEwX/
回答by David Hellsing
Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
由于用户可以进入操作系统菜单并使用鼠标选择粘贴,因此没有安全事件会为您触发此操作。我发现始终有效的唯一方法是使用 setInterval 来检查输入值是否已更改:
var inp = $('#input'),
val = saved = inp.val(),
tid = setInterval(function() {
val = inp.val();
if ( saved != val ) {
console.log('#input has changed');
saved = val;
},50);
You can also set this up using a jQuery special event.
您还可以使用 jQuery 特殊事件进行设置。