2017-04-03 156 views
0

在我的工作過程中,我嘗試通過按Enter鍵將焦點從一個文本字段移至另一個文本字段。我已經找到了可能的答案在下面的鏈接:如何將光標移動到下一個文本字段?

How to go to next textbox when enter is pressed?
Move Cursor to next text Field pressing Enter

但都未爲我工作。我的代碼:

<script> 
$('input[type='text']').keyup(function(e) { 
    if(e.keyCode == 13) { 
     $(this).next().focus(); 
    } 
}); 
</script> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
+0

關於您的實際問題在 - 它與服務器端無關。您所做的完全是客戶端,並通過將腳本標記移動到輸入下方進行修復。 –

+1

你爲什麼要用enter?從字面上看,沒有人會期望這種行爲。 – Slime

+1

@Waxi你是對的。使用Enter來進入下一個輸入將是無用的,因爲沒有人會使用它。切換輸入焦點的默認鍵是** Tab鍵**,其工作不需要javascript – Aloso

回答

1

只需更新$('input[type='text']')$('input[type="text"]')。你有沒有封閉的字符串。

Working codepen here

+0

其實我正在PHP中寫入變量$ var內的代碼。然後echo $ var。這就是爲什麼我使用$('input [type ='text']')。否則它會顯示錯誤, **解析錯誤:語法錯誤,第4行的/opt/lampp/htdocs/1.php中出現意外的'文本'(T_STRING)** –

+0

@DragonBall但是在刪除了php部分之後,解決方案Nicolae應該工作嗎? –

+0

@ Al.G。也是這個不工作,http://codepen.io/anon/pen/aJMpEj –

1

$(document).ready(function() { 
 

 
\t $('form').on('submit', function (event) { 
 
\t  event.preventDefault(); 
 
\t }) 
 

 
\t $('input[type="text"]').keyup(function(event) { 
 
\t  if(event.keyCode === 13) { 
 
     \t $(this).next().focus(); 
 
\t  } 
 
\t }); 
 

 
})
<script src="https://code.jquery.com/jquery-3.2.1.slim.js"></script> 
 
<form> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
</form>

+0

因爲jQuery不包括在內。代碼本身看起來很好。 – Aloso

+0

固定!感謝指出這一點 - 有人可以給我一個手,如何將jquery包含在片段中?這裏是一個小提琴現在:https://jsfiddle.net/qbbcmrnk/ –

0

這裏發生的事情:

<!-- Start loading the page --> 
<script> 
// execute javascript. Note that there 
// are no inputs on the page currently - they will be loaded later 

// This selector matches nothing: 
$("input[type='text']").keyup(function(e) { 
    if(e.keyCode == 13) { 
     $(this).next().focus(); 
    } 
}); 
</script> 
<!-- JavaScript executed. Now add inputs to the page --> 
<input type='text' /> 
<input type='text' /> 

你能做什麼或者是移動輸入下面的<script>(最簡單的)或移動keyup監聽到的onload功能:

$(function(){ 
// i.e. wrap your js here 

// the js here will be executed only after page has loaded 
}); 
+0

向下移動腳本將無法正常工作。 http://codepen.io/anon/pen/PpLpbp –

+0

@DragonBall抱歉,我忘記修復報價。現在應該工作。 –

+0

@ AI.G。我現在添加一個圖像。這不起作用,https://postimg.org/image/ozvdutibz/ –

相關問題