【问题标题】:How to move cursor to the next text field?如何将光标移动到下一个文本字段?
【发布时间】:2017-04-03 18:56:28
【问题描述】:

在我的工作中,我尝试通过按 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' />

【问题讨论】:

  • 关于您的实际问题 - 它与服务器端无关。您所做的完全是客户端操作,并通过将脚本标签移到输入下方来修复。
  • 为什么要使用回车?从字面上看,没有人会想到这种行为。
  • @Waxi 你是对的。使用 Enter 进入下一个输入是没有用的,因为没有人会使用它。切换输入焦点的默认键是 Tab 键,无需 javascript
  • @Al.G. : 我根据你的建议更新了代码。但它仍然无法正常工作。
  • @DragonBall 您是否使用我或其他人的答案解决了您的问题?你没有回复我最后的评论。

标签: javascript jquery


【解决方案1】:

$(document).ready(function () {

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

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

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

【讨论】:

  • 因为不包括 jQuery。代码本身看起来不错。
  • 已修复!感谢您指出这一点 - 有人可以帮我一把,如何在 sn-ps 中包含 jquery?现在有一个小提琴:jsfiddle.net/qbbcmrnk
【解决方案2】:

只需将$('input[type='text']') 更新为$('input[type="text"]')。你有未闭合的字符串。

工作代码笔here

【讨论】:

  • 实际上我是在 php.ini 的变量 $var 中编写代码。然后回显 $var。这就是我使用 $('input[type='text']') 的原因。否则会显示错误,解析错误:语法错误,第 4 行 /opt/lampp/htdocs/1.php 中的意外“文本”(T_STRING)
  • @DragonBall 但是在你删除了 php 部分之后,Nicolae 的解决方案应该可以工作吗?
  • @Al.G.而且这个也不行,codepen.io/anon/pen/aJMpEj
【解决方案3】:

这是发生了什么:

<!-- 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' />

您可以做的是将&lt;script&gt; 移动到输入下方(最简单)或将keyup 侦听器移动到onload 函数:

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

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

【讨论】:

  • @DragonBall 抱歉,我忘记修正引号了。现在应该可以了。
  • @AI.G.我现在正在添加图像。它不起作用,postimg.org/image/ozvdutibz
猜你喜欢
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多