2009-08-21 13 views

回答

211

編輯:因爲你的元素動態插入,你必須使用delegated on()在你的榜樣,但你應該把它綁定到keydown事件,因爲@Marc評論,在IE瀏覽器的按鍵事件沒有按不捕獲非字符密鑰:

$("#parentOfTextbox").on('keydown', '#textbox', function(e) { 
    var keyCode = e.keyCode || e.which; 

    if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here 
    } 
}); 

檢查示例here。 jQuery的1.9

+0

在IE8這不是爲我工作= \ – 2009-08-21 22:49:32

+0

當我按下TAB在IE6 +事件不火(它觸發的任何字母數字鍵雖然)...我需要使用.live(「按鍵」,FN) – 2009-08-21 22:55:03

+0

如果只適用於直播,也許你動態地插入你的文本框元素,如果該元素已經在頁面上,它將工作,請檢查此示例:http://jsbin.com/guhe – CMS 2009-08-21 23:01:11

12
$('#textbox').live('keypress', function(e) { 
    if (e.keyCode === 9) { 
     e.preventDefault(); 
     // do work 
    } 
}); 
+2

此外,取消默認操作,使用e.preventDefault();在函數的第一行。 – 2009-08-21 22:26:34

+0

在IE6 + – 2009-08-21 22:33:24

+0

@喬恩這不是爲我工作,按鍵不捕獲非字符鍵在IE – Marc 2009-08-21 22:34:56

17

工作例如:

$('body').on('keydown', '#textbox', function(e) { 
    if (e.which == 9) { 
     e.preventDefault(); 
     // do your code 
    } 
}); 
+1

make'e.preventDefault();'double來防止在文本框中插入空格。 – stil 2013-05-27 14:29:13

7

上述所示的方法並沒有爲我工作,可我用有點老了jQuery的,然後最後如下圖所示的代碼片段工程 - 以防萬一發佈有人在我的同一位置

$('#textBox').live('keydown', function(e) { 
    if (e.keyCode == 9) { 
     e.preventDefault(); 
     alert('tab'); 
    } 
}); 
4

使用密鑰下來標籤是知道標籤總是試圖做一些事情已經,不要忘記在年底「返回false」的一個重要組成部分。

這是我做的。我有一個運行在.blur上的函數和一個交換表單焦點位置的函數。基本上,它將輸入添加到窗體的末尾,並在模糊運行時進行。

$(this).children('input[type=text]').blur(timeEntered).keydown(function (e) { 
     var code = e.keyCode || e.which; 
     if (code == "9") { 
      window.tabPressed = true; 
      // Here is the external function you want to call, let your external 
      // function handle all your custom code, then return false to 
      // prevent the tab button from doing whatever it would naturally do. 
      focusShift($(this)); 
      return false; 
     } else { 
      window.tabPressed = false; 
     } 
     // This is the code i want to execute, it might be different than yours 
     function focusShift(trigger) { 
      var focalPoint = false; 
      if (tabPressed == true) { 
       console.log($(trigger).parents("td").next("td")); 
       focalPoint = $(trigger).parents("td").next("td"); 

      } 
      if (focalPoint) { 
       $(focalPoint).trigger("click"); 
      } 
     } 
    }); 
2

試試這個:

$('#contra').focusout(function(){ 
    $('#btnPassword').focus(); 
}); 
1

假設你有文本框的ID爲txtName的

$("[id*=txtName]").on('keydown', function(e) { 
    var keyCode = e.keyCode || e.which; 
    if (keyCode == 9) { 
    e.preventDefault(); 
    alert('Tab Pressed'); 
} 
}); 
相關問題