Javascript jquery:当我点击一个 div 时,将焦点放在一个文本框上

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

jquery: when i click a div, give focus to a textbox

javascriptjqueryfocusfocusin

提问by android.nick

$('.my-button').click(function() {
    $(".my-textbox").focus()
});

Before Jquery 1.4 this used to be the way to call focus to a textbox, now it doesn't work. When I click the button, I want to call focus to the textbox, what i mean by "focus", is that I want the textbox to act like it was just clicked on, so that the user will not have to click on the textbox.

在 Jquery 1.4 之前,这曾经是将焦点调用到文本框的方式,现在它不起作用。当我单击按钮时,我想将焦点调用到文本框,我所说的“焦点”是指我希望文本框表现得就像刚刚被点击一样,这样用户就不必点击文本框.

.focusis supposed to do an auto click onto the textbox i want it to, why isn't it working now? it broke in Jquery 1.4. I just need to know how to do it.

.focus应该自动点击我想要的文本框,为什么现在不起作用?它在 Jquery 1.4 中崩溃了。我只需要知道该怎么做。

回答by sje397

It still works. See here.

它仍然有效。见这里

reference: jQuery focus docs

参考:jQuery 焦点文档

As mentioned there, calling 'focus' on one element may trigger 'blur' on another - and so use 'focusin' instead.

正如那里提到的,在一个元素上调用“focus”可能会在另一个元素上触发“blur”——因此请改用“focusin”。

回答by Andy E

Your code works fine for me. However, it looks like you're trying to create a clickable label for an input element. If that's the case, there's an existing element named <label>that will do the job for you, no JavaScript required:

你的代码对我来说很好用。但是,您似乎正在尝试为输入元素创建可点击的标签。如果是这种情况,有一个名为的现有元素<label>可以为您完成这项工作,不需要 JavaScript:

<label for="myTextBox">I'm a label, click me</label>
<input type="text" id="myTextBox" />

Example: http://jsfiddle.net/pkk6y/

示例:http: //jsfiddle.net/pkk6y/

回答by Rudu

Those are class selectors not IDs - not sure if that's relevant, but they're inherently not unique - particularly in the focus function jquery may just plain refuse - try using IDs (and #mybutton, #mytextbox)

这些是类选择器而不是 ID - 不确定这是否相关,但它们本质上不是唯一的 - 特别是在焦点功能中 jquery 可能只是简单地拒绝 - 尝试使用 ID(和#mybutton,#mytextbox)

Update: The jQuery doc pagepoints out issues with IE:

更新:jQuery文档页面指出了 IE 的问题:

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers.

焦点事件不会在 Internet Explorer 中冒泡。因此,依赖于具有焦点事件的事件委托的脚本将无法在浏览器中一致地工作。