jQuery和setTimeout:TypeError:g.nodeName未定义

时间:2013-05-08 10:33:32

标签: javascript jquery settimeout typeerror nodename

我遇到了脚本问题。我在setTimout中使用了一个jQuery.post函数,它在Firebug上返回TypeError: g.nodeName is undefined。这是我的剧本:

jQuery(function($) {
var timer;

    $("#tabela-orcamento .item .item-qtd .qtd-item").keyup(function() {     
        clearTimeout(timer);

        timer = setTimeout(function() {         
            $.post("../../aj_orc.php?op=atualizaQtd", {
                item: $(this).parents(".item").attr("data-item"),
                qtd: $(this).val()
            }, function(data) {
                $("#retornos").html(data);
            });
        },1000);
    });
});

有问题吗?

1 个答案:

答案 0 :(得分:4)

您遇到问题,因为您的超时内的this指的是您可能想到的另一个上下文。只需引入另一个that作为中间变量:

jQuery(function($) {
    var timer;

    $("#tabela-orcamento .item .item-qtd .qtd-item").keyup(function() {     
        clearTimeout(timer);

        var $that = $(this);
        timer = setTimeout(function() {         
            $.post("../../aj_orc.php?op=atualizaQtd", {
                item: $that.parents(".item").attr("data-item"),
                qtd: $that.val()
            }, function(data) {
                $("#retornos").html(data);
            });
        },1000);
    });
});