如何使用 jQuery 或 JavaScript 聚焦 <tr> 或 <td> 标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1932152/
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
How to focus a <tr> or <td> tag using jQuery or JavaScript?
提问by teks
for(var i=0;i<tr.length;i++){
var td = tr[i].getElementsByTagName("td");
if(td[2].innerHTML==time && td[3].innerHTML==cls){
td[0].setAttribute("id","focus");
tr[i].style.backgroundColor="green";
var foc = document.getElementById("focus");
foc.focus();
cnt++;
}
else{
tr[i].style.backgroundColor="transparent";
}
}
回答by Vanco
This is a year too late, but you CANfocus to a TD element. Just give it a tabindex property, and then do a focus().
这是一年为时已晚,但你CAN专注于TD元素。只需给它一个tabindex 属性,然后执行focus()。
This works for DIV elements and almost all others.
这适用于 DIV 元素和几乎所有其他元素。
I've tried this on Firefox 3.5 and up.
我已经在 Firefox 3.5 及更高版本上尝试过这个。
回答by kiamlaluno
As the question is about changing the focus on a TD or TR, then the answer is that you cannot focus on such HTML tags; you can change the currently focused element if that is a input element (textarea, textfield, checkbox, radios) or a link, which are highlighted in a particular way when you click the key tab.
If you are really trying to focus on an input field, as suggested by Jonathan Sampson, then the answer he gave is the correct one.
由于问题是关于改变对 TD 或 TR 的关注,那么答案是您不能关注此类 HTML 标签;您可以更改当前聚焦的元素,如果它是输入元素(文本区域、文本字段、复选框、单选框)或链接,当您单击键选项卡时以特定方式突出显示。
如果您真的像 Jonathan Sampson 建议的那样专注于输入字段,那么他给出的答案就是正确的答案。
In your code you are really trying to get the focus on a tag TD, then the answer to the question is no.
在您的代码中,您确实试图将注意力集中在标签 TD 上,那么问题的答案是否定的。
回答by Sampson
It appears you have an input field with the id "focus" within a td, so I'm assuming you want to focus on that input itself. With jQuery, you would do this:
看来您在 td 中有一个 ID 为“focus”的输入字段,所以我假设您想专注于该输入本身。使用 jQuery,你可以这样做:
$("input#focus").focus();
This will cause the focus to be brought to that particular element once called. I see that you also tried setting the ID of a particular TD to "focus" as well; you should only use a unique ID value once per page. If you feel the need to use a single value to represent many elements, consider using classnames instead as there can exist any number of them on a page.
一旦调用,这将导致焦点被带到该特定元素。我看到您还尝试将特定 TD 的 ID 设置为“焦点”;您应该每页只使用一次唯一的 ID 值。如果您觉得需要使用单个值来表示多个元素,请考虑使用类名,因为页面上可以存在任意数量的类名。

