javascript 焦点不适用于输入

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

focus not working for input

javascriptjqueryhtml

提问by user3487944

MY focus is not working

我的注意力不集中

Code on JSFiddle:

JSFiddle上的代码:

http://jsfiddle.net/JLULx/

http://jsfiddle.net/JLULx/

HTML

HTML

<body>
    Email1<input type="email"><br/>

    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="selectors.js" type="text/javascript"></script>
</body>

Script ...

脚本 ...

$(document).ready(function () {

    var email_default = "Enter your Email address";
    $('input [type="email"]').focus();
});

similar post :

类似的帖子:

  1. $.focus() not working
  1. $.focus() 不工作

it says $(document).readyfunction should load completely and focus should be shift from console..how to do it . I could't understand ...

它说$(document).ready函数应该完全加载并且焦点应该从控制台转移..怎么做。我无法理解...

2.jQuery focus function not working in Firefox

2. jQuery 焦点功能在 Firefox 中不起作用

This is doesnt seem to be relevant ..

这似乎不相关..

Please suggest

请建议

采纳答案by Ryan

To check if jQuery returned an object do this:

要检查 jQuery 是否返回了一个对象,请执行以下操作:

if($('.my-selector').length)) {
  // jQuery returned an object
}

You have an extra space in your selector. jQuery thinks your trying to access a child element of an inputelement. You need to change your code to this:

您的选择器中有一个额外的空间。jQuery 认为您尝试访问元素的子input元素。您需要将代码更改为:

$('input[type="email"]').focus();

Also be sure that you are loading the jQuery library before you load your custom JavaScript.

还要确保在加载自定义 JavaScript 之前加载 jQuery 库。

http://jsfiddle.net/JLULx/2/

http://jsfiddle.net/JLULx/2/

回答by Eduardo

Why don't you use an ID for the email field.

为什么不为电子邮件字段使用 ID。

Example:

例子:

<input id="input-email" type="email"/>


$("#input-email").focus()

A more simple way is to use the HTML5 autofocus feature:

更简单的方法是使用 HTML5 自动对焦功能:

<input type="email" autofocus="true">

回答by Eduardo

Mmmmm, I think the problem is with JSFiddle.

嗯,我认为问题出在 JSFiddle 上。

For example if you run $("#run") on the browser console. It returns "null". It's supposed the ID "run" belongs to the run button on JSFiddle

例如,如果您在浏览器控制台上运行 $("#run")。它返回“空”。它应该 ID“运行”属于 JSFiddle 上的运行按钮

回答by Vijay

There are two things missing on you fiddle - 1. You haven't included proper jQuery library instead trying with pure JS. 2. in your selector remove the space between 'input' and '[type="email"]'. (as answered by RPM)

您的小提琴缺少两件事 - 1. 您没有包含正确的 jQuery 库,而是尝试使用纯 JS。2. 在您的选择器中删除'input' 和'[type="email"]' 之间的空格。(如 RPM 所回答)