gpt4 book ai didi

javascript - 为什么是 $ ('[tabindex="1"]' ).focus();关注 tabindex ="2"?

转载 作者:行者123 更新时间:2023-11-28 12:27:06 27 4
gpt4 key购买 nike

当提交按钮获得焦点时按 Tab 键,焦点应返回到 tabindex="1"。这是 HTML:

<input tabindex="1" id="tabindex1" value="tabindex='1'" autofocus>
<input tabindex="2" id="tabindex2" value="tabindex='2'">
<input tabindex="3" id="tabindex3" value="tabindex='3'">
<input tabindex="4" id="submit_button" type="submit">

这是 JQuery:

$("input").keydown(function (e) {
if (e.which == 9 && $(":focus").attr("id") == "submit_button") {
$('[tabindex="1"]').focus(); // Focuses on tabindex="2"!!!
// $('#tabindex1').focus(); // Does the same thing
}
});

here's the fiddle 。对于我的一生,我无法弄清楚为什么它会使用 tabindex="2" 而不是 tabindex="1",甚至当我这样做时它也会这样做使用 id 属性而不是 tabindex。如何让它转到 tabindex="1"

更新:以下解决方案来自 soktinpkhobbs成功了。 Here's a fiddle显示它与 return false; 一起使用,这是一个 fiddle ,显示它与 e.preventDefault(); 一起使用。后续问题:这两种解决方案中的一种优于另一种吗?

最佳答案

return false 添加到 if 语句的末尾:

$("input").keydown(function (e) {
if (e.which == 9 && $(":focus").attr("id") == "submit_button") {
$('[tabindex="1"]').focus(); // Focuses on tabindex="2"!!!
// $('#tabindex1').focus(); // Does the same thing
return false;
}
});
<input tabindex="1" id="tabindex1" value="tabindex='1'" autofocus>
<input tabindex="2" id="tabindex2" value="tabindex='2'">
<input tabindex="3" id="tabindex3" value="tabindex='3'">
<input tabindex="4" id="submit_button" type="submit">

问题是,它专注于第一个输入,然后浏览器执行默认操作,即专注于下一个输入。因此,最终,它关注的是第二个输入。

返回 false 可确保浏览器不采用默认行为。

关于javascript - 为什么是 $ ('[tabindex="1"]' ).focus();关注 tabindex ="2"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093262/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com