无法使用"in"运算符在未定义的位置搜索"sth" [英] Cannot use 'in' operator to search for 'sth' in undefined

查看:314
本文介绍了无法使用"in"运算符在未定义的位置搜索"sth"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

.
.
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});
}
.
.

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

As I've commented, third line throws this error:

未捕获的TypeError:无法使用'in'运算符搜索未定义的'abort'

Uncaught TypeError: Cannot use 'in' operator to search for 'abort' in undefined

我该如何解决?

推荐答案

此处的问题是

The issue here is that the undefined value does not have any properties. You need to perform a check on the return value of data() to check that it isn't undefined.

var xhr = $(this).data('xhr');
if(typeof xhr !== 'undefiend' && xhr.abort) {
    // do your code here
}

用以上4行代码替换您的if语句.

Replace your if statement with the above 4 lines of code.

这篇关于无法使用"in"运算符在未定义的位置搜索"sth"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆