我想检测文本框的内容何时发生了变化。我可以使用keyup方法,但这也将检测不生成字母的击键,如方向键。我想到了两种使用keyup事件的方法:

显式检查所按键的ascii码是否为字母\backspace\delete 使用闭包来记住在击键之前文本框中的文本是什么,并检查这是否已更改。

两者看起来都有点麻烦。


当前回答

“change”事件不能正常工作,但“input”是完美的。

$('#your_textbox').bind('input', function() {
    /* This will be fired every time, when textbox's value changes. */
} );

其他回答

document.getElementById('txtrate' + rowCount).onchange = function () {            
       // your logic
};

这个工作得很好,但在点击时也会触发事件,这并不好。我的系统进入循环。 而

$('#txtrate'+rowCount).bind('input', function() {
        //your logic
} );

在我的场景中非常适用。它只在值改变时起作用。 可以使用document代替$ sign。getElementById太

在HTML/标准JavaScript中使用onchange事件。

在jQuery中这就是change()事件。例如:

$('element').change(function() {// do something});

EDIT

看了一些评论后,你觉得:

$(function() {
    var content = $('#myContent').val();

    $('#myContent').keyup(function() { 
        if ($('#myContent').val() != content) {
            content = $('#myContent').val();
            alert('Content has been changed');
        }
    });
});

这个怎么样:

< jQuery 1.7

$("#input").bind("propertychange change keyup paste input", function(){
    // do stuff;
});

jQuery 1.7

$("#input").on("propertychange change keyup paste input", function(){
    // do stuff;
});

这适用于IE8/IE9, FF, Chrome

使用textchange事件通过定制的jQuery shim跨浏览器输入兼容性。http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html(最近分叉github: https://github.com/pandell/jquery-splendid-textchange/blob/master/jquery.splendid.textchange.js)

这处理所有输入标签,包括<textarea>内容</textarea>,这并不总是与改变keyup等工作(!)只有jQuery on("input propertychange")处理<textarea>标签一致,以上是对所有不理解输入事件的浏览器的一个填充。

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/pandell/jquery-splendid-textchange/master/jquery.splendid.textchange.js"></script>
<meta charset=utf-8 />
<title>splendid textchange test</title>

<script> // this is all you have to do. using splendid.textchange.js

$('textarea').on("textchange",function(){ 
  yourFunctionHere($(this).val());    });  

</script>
</head>
<body>
  <textarea style="height:3em;width:90%"></textarea>
</body>
</html>

JS Bin测试

这还可以处理粘贴、删除,并且不会重复keyup上的工作。

如果不使用shim,请使用jQuery on("input propertychange")事件。

// works with most recent browsers (use this if not using src="...splendid.textchange.js")

$('textarea').on("input propertychange",function(){ 
  yourFunctionHere($(this).val());    
});  

你考虑使用变化事件吗?

$("#myTextBox").change(function() { alert("content changed"); });