有没有办法捕捉textarea的变化?

时间:2012-09-25 19:16:34

标签: javascript jquery

以下是我现在正在使用的内容

$("#text").on("input", function(event){

    console.log("The changes are:" + SomeDataThatIDontKnowHowToAccess);

});

我意识到这可能会破坏退格/粘贴文本/插入/删除。我真的不知道如何处理这个问题,可能有删除/插入/覆盖事件...我宁愿不推出自己的解决方案。

示例

用户将something粘贴到空白文本区域

{eventType:'insert', value:'something'}

显示在控制台中

4 个答案:

答案 0 :(得分:1)

将旧值写入可以保持焦点的某个位置。然后,您可以在change事件中使用自己的逻辑来查找旧值和新值之间的差异

$('#text').on('focus', function () {
    //THIS LINE IS INCORRECT [what was wrong with my fiddle]... assignment is parameter *doh*
    //$(this).data('oldValue') = $(this).val();
    //THIS IS THE CORRECT LINE
    $(this).data('oldValue', $(this).val());
}).on('change', function() {
    alert('Old Value: ' + $(this).data('oldValue') + '\nNew Value: ' + $(this).val());
});

小提琴:http://jsfiddle.net/BLSully/jqbAr/1/ [已修复]

答案 1 :(得分:1)

你必须在这做两件事。首先,您必须缓存最后一个值。这样,当新值出现时,您可以将其与之进行比较。

其次,您需要查看(并下载)string diff function made available by John Resig。你会将diff的输出变成div的html。结果看起来很棒。

然后,您的解决方案将如下所示:

$("#text").data('lastvalue', $("#text").val());
$("#text").on("input", function(event){
    var diff = diffString($("#text").data('lastvalue'), $("#text").val()); 
    $('#changesdiv').html("The changes are:" + diff);
    $("#text").data('lastvalue', $("#text").val());
});​

<强>更新

我在脚本上修复了一些错误,并在http://jsfiddle.net/m3KAa/6/

运行了一个jsfiddle

恕我直言,这个diffString功能非常棒。

答案 2 :(得分:0)

试试这个

//当textarea失去焦点时可以使用此事件

$("#text").on("change", function(event){

    console.log("The changes are:" + $(this).val() );

});

//此事件可用于用户开始输入和密钥被提取

 $("#text").on("keyup", function(event){

        console.log("The changes are:" + $(this).val() );

    });

//

$("#text").on("input",   // Here input is not a event you are supposed to used

//尝试使用更改事件..

答案 3 :(得分:0)

如果您需要获取当前值,则需要使用keyup事件

$("#text").on("keyup ", function(event){
    console.log("The changes are:" + $(this).val() );
});
相关问题