当按键更改文本框的输入时,我想做一些事情。我认为这个keypress事件最适合这个,但我怎么知道它是否引起了变化?我需要过滤掉诸如按箭头键或修饰符之类的东西……我不认为对所有值进行硬编码是最好的方法。
那我该怎么做呢?
当按键更改文本框的输入时,我想做一些事情。我认为这个keypress事件最适合这个,但我怎么知道它是否引起了变化?我需要过滤掉诸如按箭头键或修饰符之类的东西……我不认为对所有值进行硬编码是最好的方法。
那我该怎么做呢?
在大多数浏览器中,您可以input对文本类型<input>元素使用 HTML5事件:
$("#testbox").on("input", function() {
alert("Value changed!");
});
这在 IE < 9 中不起作用,但有一个解决方法:propertychange事件。
$("#testbox").on("propertychange", function(e) {
if (e.originalEvent.propertyName == "value") {
alert("Value changed!");
}
});
IE 9 两者都支持,因此在该浏览器中最好选择基于标准的input事件。这很方便首先触发,因此我们可以删除propertychange第一次input触发的处理程序。
把它们放在一起(jsFiddle):
var propertyChangeUnbound = false;
$("#testbox").on("propertychange", function(e) {
if (e.originalEvent.propertyName == "value") {
alert("Value changed!");
}
});
$("#testbox").on("input", function() {
if (!propertyChangeUnbound) {
$("#testbox").unbind("propertychange");
propertyChangeUnbound = true;
}
alert("Value changed!");
});
.change()是你所追求的
$("#testbox").keyup(function() {
$(this).blur();
$(this).focus();
$(this).val($(this).val()); // fix for IE putting cursor at beginning of input on focus
}).change(function() {
alert("change fired");
});
这就是我的做法:http : //jsfiddle.net/JesseAldridge/Pggpt/1/
$('#input1').keyup(function(){
if($('#input1').val() != $('#input1').attr('prev_val'))
$('#input2').val('change')
else
$('#input2').val('no change')
$('#input1').attr('prev_val', $('#input1').val())
})
我想出了这个来自动保存文本区域。它结合使用.keyUp()jQuery 方法来查看内容是否已更改。然后我每 5 秒更新一次,因为我不希望表单每次更改时都被提交!!!!
var savePost = false;
jQuery(document).ready(function() {
setInterval('autoSave()', 5000)
$('input, textarea').keyup(function(){
if (!savePost) {
savePost = true;
}
})
})
function autoSave() {
if (savePost) {
savePost = false;
$('#post_submit, #task_submit').click();
}
}
我知道即使内容没有改变它也会触发,但是硬编码我不希望它为哪些键工作更容易。