这是我的代码:

.
.
keydown: function(ev) {

    clearTimeout( $(this).data('timer') );
    if ( 'abort' in $(this).data('xhr') ) $(this).data('xhr').abort();       // error here
    var xhr, timer = setTimeout(function() {
        xhr = $.ajax({
            url :  '/files/tags_autocomplete.php',
            dataType : 'JSON',
            success : function (tags) {
            $("ul").html(tags.output);
            }
        });
    }, 500);

    $(this).data({timer : timer, xhr : xhr});
}
.
.


正如我所评论的,第三行抛出此错误:


  Uncaught TypeError:无法使用'in'运算符在未定义中搜索'abort'


我该如何解决?

最佳答案

更改自:

if ('abort' in $(this).data('xhr') ) $(this).data('xhr').abort();


至:

if ($(this).data('xhr') && $(this).data('xhr').abort) {
  $(this).data('xhr').abort();
}


问题只是检查对象是否具有xhr元素。默认情况下它不存在,所以它是undefined,并且您要JS引擎在undefined信息中查找引起错误的元素。

所以这就是为什么我要检查它是否具有.data('xhr')的原因,因为对于JS undefined被视为false,然后检查data('xhr')是否具有abort属性。

顺便说一句,如果您想在按下键时停止计时器,最好只是清除超时,并且它不会运行AJAX调用,因此不需要将XHR对象放入元素的数据存储中:

if($(this).data('timer')) {
  clearTimeout($(this).data('timer'));
}

var timer = setTimeout(function() {
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
          $("ul").html(tags.output);
        }
    });
}, 500);

$(this).data('timer', timer);


甚至更简单(没有数据存储):

if(window.autocompleteTimer) {
  clearTimeout(window.autocompleteTimer);
}

window.autocompleteTimer = setTimeout(function() {
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
          $("ul").html(tags.output);
        }
    });
}, 500);

07-28 02:26
查看更多