2016-09-27 30 views
0

這裏搜索「某事」是我的代碼:不能使用「在」運營商在不確定的

. 
. 
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: Cannot use 'in' operator to search for 'abort' in undefined

哪有我修復它?

+0

[IN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)是用來尋找一個屬性在一個對象或數組中,我不認爲'$(this).data(「xhr」)'是 –

+0

@SterlingArcher'$(this).data(「xhr」)'是'xhr'的值變量,它是'$ .ajax'返回的'jqXHR'對象。 – Barmar

+0

拍攝,我認爲這是一個數據屬性。我的錯。 –

回答

2

更改從:

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); 
+3

'$(this).data('xhr')'似乎是一個很好的候選變量。 – 4castle

+0

@ 4castle haha​​(:我剛剛給出了問題的解決方案,但是在數據屬性中保留對象和/或函數是不對的 – num8er

2

這裏的問題是,undefined值沒有任何屬性。您需要檢查返回值data()以檢查它是否未定義。

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

用上面的4行代碼替換您的if語句。

1

問題是,如果用戶在500ms過去之前再次鍵入,$(this).data('xhr')可能是未定義的,因爲它尚未設置爲ajax請求。

正如我們不能使用in操作上undefined,只有在對象上,正確的解決方案既清除超時並中止任何掛起的請求,是隻檢查是否$(this).data('xhr')已定,並且是一個對象,之前檢查它是否有一個abort屬性

keydown: function(ev) { 
    var self = $(this); 

    clearTimeout(self.data('timer')); 

    if (typeof self.data('xhr') === 'object' && 'abort' in self.data('xhr')) { 
    self.data('xhr').abort(); 
    } 

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

    self.data('timer', timer);