Javascript JQuery 聚焦一个元素

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

JQuery focus an element

javascriptjquery

提问by stealthcopter

In javascript the following works to give focus to the edit_2 input box:

在 javascript 中,以下工作将焦点放在 edit_2 输入框上:

document.getElementById("edit_2").focus();

However using Jquery this does not:

但是使用 Jquery 这不会:

$("#edit_2").focus;

回答by Alex Bagnolini

You are calling a method, so:

您正在调用一个方法,因此:

$("#edit_2").focus;

should be

应该

$("#edit_2").focus();

EDIT: If you are wondering why the first line was not counted as a syntax error, it's because it is a correct statement saying "get the function focus" (and do nothing with it).

编辑:如果您想知道为什么第一行不被算作语法错误,那是因为它是一个正确的语句,说“获取函数focus”(并且什么也不做)。

回答by Arun P Johny

Your statement

你的陈述

$("#edit_2").focus

is not calling the function 'focus', in order to call the function you have to use the syntax 'focus()'

不是调用函数“focus”,为了调用该函数,您必须使用语法“focus()”

try

尝试

j$("#some_id").focus()

It is working fine.

它工作正常。

EDITYour statement '$("#edit_2").focus' is not throwing an error because it just returns a reference to the function 'focus', but it does not call the function.

编辑您的语句 '$("#edit_2").focus' 没有抛出错误,因为它只是返回对函数 'focus' 的引用,但它没有调用该函数。

回答by wsanville

focusis a function and must be called like one, change your code to look like:

focus是一个函数,必须像一个函数一样调用,将您的代码更改为:

$("#edit_2").focus();

For reference, see focus documentation.

如需参考,请参阅焦点文档