簡體   English   中英

運行功能如果用戶刪除單詞

[英]Run Function If user delete the word

因此,我有一個用於將關鍵字發送到另一個頁面的jQuery代碼。在該頁面上,我擁有所有國家/地區的名稱。 我的代碼也很好用,我在以下情況下定義了我的函數:如果輸入文本的長度大於2,則在其中運行該函數,但是,例如,當我編寫城市名稱時,我對此有問題並從ajax頁面返回正確的數據,我的問題是,當用戶想要用退格鍵或其他東西刪除該單詞時,我想刪除所有先前發送到ajax頁面的數據,但是由於我的情況,它不起作用。

如何定義用戶是否刪除運行我的功能的單詞?

這是我的代碼:

 var prevXHR = null; //global $('.country').each(function() { $(this).on('keyup', function(e) { var _this = this; var element = $(this).val().length; if (e.which !== 0 && !e.ctrlKey && !e.metaKey && !e.altKey ){ if (element > 2) { var val = $(this).val() $(this).val(val) prevXHR = $.ajax({ url: "ajaxpage.htm", type: "get", contentType: 'application/json; charset=utf-8', data: { key: $(this).val() }, success: function(result) { $(_this).closest(".search_div").find(".co").empty().html(result) }, beforeSend: function(){ if(prevXHR && prevXHR.readyState != 20){ //before sending any new request neutralize any pending ajax call prevXHR.abort(); prevXHR = null; } } }); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="search_div"> <input type="text" value="" class="country" autocomplete="off" /> <div class="result"></div> </div> 

在您的代碼中,您已經在檢查輸入的長度是否大於2,然后繼續進行ajax調用。

然后再添加else部分。

if (element > 2) {
    // ...do the ajax stuff here
} else {
   // the input length was shorter than 2 characters...

   // remove all HTML elements here

   $('div#to_be_removed').remove();   //or something like that

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM