使用 jQuery 在文本框中设置焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2339870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting focus in textbox using jQuery
提问by haansi
I am doing a small jQuery function. What this function should do is on leaving textbox it should display text from textbox as alert, clears textbox and again set focus in the same textbox. It is doing two of three tasks showing text in alert and clearing textbox but it is not setting focus back in that textbox.
我正在做一个小的 jQuery 函数。这个函数应该做的是在离开文本框时它应该将文本框中的文本显示为警报,清除文本框并再次在同一文本框中设置焦点。它正在执行在警报和清除文本框中显示文本的三个任务中的两个,但它没有将焦点重新设置在该文本框中。
Please note this textbox is in a form and I have used tab index here as well. When I clicked ok in alert it move focus to the next textbox having next tab index.
请注意这个文本框是一个表单,我在这里也使用了标签索引。当我在警报中单击确定时,它将焦点移到下一个具有下一个标签索引的文本框。
Here is my code:
这是我的代码:
<script type="text/javascript">
function pageLoad() {
$("input[id$='txtEmailAddress']").blur(CheckOnServer);
}
function CheckOnServer() {
alert($("input[id$='txtEmailAddress']").val());
$("input[id$='txtEmailAddress']").val("");
$("input[id$='txtEmailAddress']").focus();
alert("2");
}
</script>
采纳答案by monksp
If there's more than one field ending with 'txtEmailAddress', wouldn't your code be trying to assign focus to each of them at the same time? I'm thinking that the wrong field is gaining focus because $(input[id$='txtEmailAddress']
isn't a single DOM element, and jQuery isn't designed to run the focus function on an array of objects.
如果有多个以“txtEmailAddress”结尾的字段,您的代码不会尝试同时为每个字段分配焦点吗?我认为错误的领域正在获得焦点,因为$(input[id$='txtEmailAddress']
它不是单个 DOM 元素,并且 jQuery 不是为了在对象数组上运行焦点函数而设计的。
I agree with Adrian, though. If you get it to work the way that you want, you will neverbe able to leave that field. If you want it to do the 'alert, clear, refocus' dance just one time, remember to clear the onblur function afterwards.
不过,我同意阿德里安的观点。如果你让它以你想要的方式工作,你将永远无法离开那个领域。如果你想让它只做一次“警报、清除、重新聚焦”的舞蹈,记得在之后清除 onblur 功能。
回答by Adrian Schmidt
Attaching the CheckOnServer function to the blur event of your input field seems really weird to me. I haven't tested your code, so I might be wrong, but as I see it, this is saying:
将 CheckOnServer 函数附加到输入字段的模糊事件对我来说似乎很奇怪。我还没有测试过你的代码,所以我可能是错的,但在我看来,这是说:
When input[id$='txtEmailAddress']
loses focus, do some stuff, and give it focus again. This is gonna be a never ending loop...
当input[id$='txtEmailAddress']
失去焦点时,做一些事情,然后重新集中注意力。这将是一个永无止境的循环......
As to why the wrong field is gaining focus, I have no better idea than Ben.
至于为什么错误的领域正在获得关注,我没有比 Ben 更好的想法。