2014-11-23 103 views
0

在提交按鈕處於焦點時按下選項卡時,焦點應返回到tabindex="1"。這裏的HTML:

<input tabindex="1" id="tabindex1" value="tabindex='1'" autofocus> 
<input tabindex="2" id="tabindex2" value="tabindex='2'"> 
<input tabindex="3" id="tabindex3" value="tabindex='3'"> 
<input tabindex="4" id="submit_button" type="submit"> 

而這裏的JQuery的:

$("input").keydown(function (e) { 
    if (e.which == 9 && $(":focus").attr("id") == "submit_button") { 
     $('[tabindex="1"]').focus(); // Focuses on tabindex="2"!!! 
     // $('#tabindex1').focus(); // Does the same thing 
    } 
}); 

而且here's the fiddle。對於我的生活,我不知道爲什麼它會去tabindex="2"而不是tabindex="1",甚至當我使用id屬性而不是tabindex時,它也會這樣做。我如何得到它tabindex="1"

更新:從soktinpkhobbs下面的解決方案做了伎倆。 Here's a fiddle顯示它與return false;一起使用,這裏是一個小提琴,顯示它與e.preventDefault();一起使用。後續問題:這兩種解決方案中的哪一種比另一種更好?

+0

將'return false'添加到'if'語句。 – soktinpk 2014-11-23 19:27:36

回答

4

添加return falseif聲明的末尾:

$("input").keydown(function (e) { 
    if (e.which == 9 && $(":focus").attr("id") == "submit_button") { 
     $('[tabindex="1"]').focus(); // Focuses on tabindex="2"!!! 
     // $('#tabindex1').focus(); // Does the same thing 
     return false; 
    } 
}); 
<input tabindex="1" id="tabindex1" value="tabindex='1'" autofocus> 
<input tabindex="2" id="tabindex2" value="tabindex='2'"> 
<input tabindex="3" id="tabindex3" value="tabindex='3'"> 
<input tabindex="4" id="submit_button" type="submit"> 

的問題是,它的重點在第一個輸入上,然後瀏覽器執行默認操作,該操作將重點放在下一個輸入上。所以最終它將重點放在第二個輸入上。

返回false可確保瀏覽器不採取默認行爲。

+1

或者,'e.preventDefault()'。 – Oriol 2014-11-23 19:51:09

2

您不會阻止默認操作,並且選項卡的默認操作將移至下一個tabindex。所以,你的回調重點的tabIndex 1,然後TAB鍵的默認行爲集中的tabindex 2.