Jquery:我如何检测内容更改? (寻找keyup()的替代品)

时间:2012-11-30 14:53:07

标签: jquery

我使用这个简单的Jquery代码从div获取元素,然后通过php脚本更改它:

$(document).ready(function(){
    $("#description").keyup(function(){
    var recherche = $(this).val();

    $.ajax({
        type : "GET",
        url : "result.php",
        data : {motclef: recherche},
        success: function(server_response){
        $("#resultat").html(server_response).show();
        }
    });
});

});

问题是在没有按任何键(复制/过去......)的情况下可能会发生一些变化。我尝试过.change()但只有当元素的焦点丢失时才会触发它。

1 个答案:

答案 0 :(得分:1)

你可以告诉jQuery在一次调用中绑定到多个事件,就像这样。 进入方法后,您可以根据事件类型过滤行为。处理粘贴时,通常最好稍微延迟函数调用,以允许浏览器首先执行所需的所有操作。

修改

我已根据此stackoverflow answer更新了答案,以便处理自动填充。

$("#description").on("keyup paste cut focus change blur",function (event) {

    var $this = $(this),
        delay = 0

    // Add delay for cut/paste
    if (event.type === "paste" || event.type === "cut") {
        delay = 5;
    }

    // Record the current value of the text box.
    if (event.type === "focus" || event.type === "change") {
        this.previousvalue = this.value;
    }

    // Trigger the change event if the value is now different.
    if (event.type === "blur") {
        if (this.previousvalue !== this.value){
            $this.change();
            return false;
        }
    }

    window.setTimeout(function () {

        var recherche = $this.val();

        $.ajax({
            type : "GET",
            url : "result.php",
            data : {motclef: recherche},
            success: function(server_response){
                $("#resultat").html(server_response).show();
            }
        });                  

    }, delay);
});