2011-10-13 64 views
0

我有一個輸入字段的列表,當我通過他們選項卡我想循環回到第一個,但它似乎並沒有工作。焦點()似乎不工作後onblur()

這裏是我的HTML

<form id="form"> 
    <input id="mon" type="text"/> Month<br> 
    <input id="day" type="text"/> Day<br> 
    <input id="num" type="text"/> Year<br> 
    <input id="amt" type="text"/> Amount<br> 
</form> 

和我的javascript

window.onload=function(){ 
    $('mon').focus(); 
    $('amt').onblur=function(){ 
    //Process the input fields 
    $('mon').focus(); 
    } 
} 
function $(a){return document.getElementById(a)} 
+0

難道你不需要在你的ID選擇器上有一些#號? – sethobrien

+0

@sethobrien - 這不是jQuery ...查看問題中定義的'$'函數。 –

+0

我的不好。我使用控制檯在SO頁面中設置了您要描述的內容,並且在我將標籤放在答案框外時,對搜索框進行聚焦似乎沒有問題。你可以發佈一個jsfiddle嗎? – sethobrien

回答

1

我覺得你onblur事件處理程序的默認處理程序之前被調用,導致重點先切換到輸入「星期一」,然後到瀏覽器認爲應該關注的任何內容。嘗試使用onkeypress事件。例如

window.onload=function(){ 
    $('mon').focus(); 
    $('amt').onkeydown = function(e) { 
    //check for IE weirdness 
    if (e === undefined && event !== undefined) 
     e = event; 
    if (e.keyCode == 9) { 
     $('mon').focus(); 
     return false; 
    } 
    } 
} 
function $(a){return document.getElementById(a)} 

編輯:onkeydown實際上似乎工作,更多的瀏覽器

編輯2:添加IE情況。 IE並不總是將事件作爲參數傳遞

+0

我希望有一個更優雅的答案,但它的工作原理。 – qw3n

0

要使光標出現在第一個輸入框上,您需要將輸入框的值分配給自己(hack)。你也需要「返回false」來停止事件傳播。修改後的模糊功能如下,

<input id="mon" type="text" onfocus="this.value=this.value;" /> 

$('amt').onblur = function(){ $('mon').focus(); return false; } 
+0

你測試過什麼瀏覽器?它在Firefox 7或Chromium 13中不適用於我。 – Ben

0

看看這個小提琴。我認爲這是你想達到的。 http://jsfiddle.net/CucuIonel/7Fpu3/7/

+0

在Firefox 7中,這不起作用。 「月」輸入框將在「金額」框中跳出後突出顯示,但無法輸入。 – Ben

+0

我有Firefox 7,它適用於我,因爲它在小提琴中。 –