jQuery 使用jquery加载页面后如何在文本框中设置光标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7623827/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:04:28  来源:igfitidea点击:

How set cursor inside textbox after page load with jquery

jquerytextboxcursor

提问by MonsterMMORPG

Alright i have a asp.net textbox and i want to set cursor inside textbox after page loaded like when you open google.

好吧,我有一个 asp.net 文本框,我想在页面加载后在文本框中设置光标,就像打开谷歌一样。

I only need set cursor inside textbox code.

我只需要在文本框代码中设置光标。

I tried this but not working

我试过这个但没有用

$('txtSendTo').focus();

回答by Jason Gennaro

If txtSendTois an id, you need a #

如果txtSendToid,你需要一个#

$('#txtSendTo').focus();

$('#txtSendTo').focus();



If txtSendTois a class, you need a .

如果txtSendTo是 a class,你需要一个.

$('.txtSendTo').focus();

$('.txtSendTo').focus();



Or, if there is only one textboxon the page

或者,如果textbox页面上只有一个

$('textbox').focus();

$('textbox').focus();



Also make sure the page is fully loaded before you try to search the dom:

在尝试搜索 dom 之前,还要确保页面已完全加载:

$(document).ready(function () {
  `$('textbox').focus();`
});

回答by Usman Shaukat

I was not able to set cursor inside an input field when a link is clicked. However adding event.preventDefault() at the start of the function and returning false fixed it. Here is the code if someone is having the same issue

单击链接时,我无法在输入字段内设置光标。但是在函数的开头添加 event.preventDefault() 并返回 false 修复了它。如果有人遇到同样的问题,这是代码

$("#search-button").click(function (event) {
  event.preventDefault();
  $("#textbox").focus();
  return false;
});