2013-10-29 102 views
1

我有一個輸入和一個事件處理程序連接到它,由於某種原因,keyup事件不起作用。我已經看了一會兒,卻無法弄清楚問題所在。當我在輸入框中輸入內容時,警告窗口甚至不顯示。Jquery沒有觸發keyup

$(function() { 
    var tagField = $("#<%= EditTagNum.ClientID %>"); //asp.net code to get the generated client ID 

    $(tagField).on('keyup paste cut', function() { 
     alert('inside event handler'); 
     var _this = this; 
     //because the paste event fires before the text has actually been 
     //pasted, I have to set a timeout. Once the timeout occurs, the text 
     //has then been entered into the input box. 
     setTimeout(function() { 
      var text = $(_this).val(); 
      $(_this).val(text.replace(/\D/g, '')); 
     }, 0); 
    }); 
}); 

更新: 我改變了我的代碼直接使用生成的客戶端ID爲這樣:

$( 「#ctl00_ContentPlaceHolder1_EditTagNum」)上(.....

這並沒有解決問題,但我確實發現,一旦我在控制檯中運行我的事件處理函數, 有用。這是如果事件處理程序從未附加。然而,當我在Chrome中進行調試時,我發現它到達了附加處理程序的函數。它從來沒有進入它的內部。

+0

在這裏使用你的代碼,並嘗試jQuery選擇器的靜態元素ID:http://jsfiddle.net/SZG9B/看起來像它工作正常。檢查並確保傳遞給jQuery的參數/元素是有效/存在的。 –

+0

如果警報未觸發,您可能有語法錯誤,或者沒有從服務器端代碼獲取正確的選擇器。 – adeneo

+1

在'var tagField = ...'之後執行'console.log(tagField.length)'來查看元素是否被找到。另外,'tagField'已經是一個jquery對象,您不需要執行'$(tagField)' –

回答

1

您可以檢查,如果這個工程:

$(tagField).keyup(function() { 

,而不是

$(tagField).on('keyup paste cut', function() { 
0
var tagField = $("#<%= EditTagNum.ClientID %>"); 

這裏tagField本身是一個jQuery對象。並且你正在用jquery再次包裝這個對象。請嘗試以下操作:

tagField.on('keyup paste cut', function() { 
     alert('inside event handler'); 
     var _this = this; 
     //because the paste event fires before the text has actually been 
     //pasted, I have to set a timeout. Once the timeout occurs, the text 
     //has then been entered into the input box. 
     setTimeout(function() { 
      var text = $(_this).val(); 
      $(_this).val(text.replace(/\D/g, '')); 
     }, 0); 
    }); 
}); 

它應該工作。

+0

試過了,它沒有解決我的問題。 – Justin

0

取而代之:'keyup粘貼剪切',試試這個..「keyup粘貼剪切」.. 神奇地在過去...爲我工作...! :)

+0

使用雙引號或單引號不應有所作爲 - 它更多是一種文體選擇。 – Terry

0

您可以使用

$(document).on('keyup', tagField, function() {...}); 

相反,如果你不能確定tagField在您調用$(tagField)。在( 'KEYUP',tagfield時被附加到DOM。 ..);