jQuery .focus()无效

时间:2014-08-25 05:50:58

标签: javascript jquery html css

以下实现是针对一组三个单选按钮,其CSS中的按钮与标签配对display :none

现在我一直在尝试向页面添加一些辅助功能选项,以便您可以使用箭头键在单选按钮上导航,更改每个按键上标签的焦点。但我不能,因为我的生活让它改变了焦点,重点仍然放在标签上的初始标签上。

我已经尝试了一些我在这里看到的关于超时的选项,并在我开始时启用tabIndex(希望它作为一个组),没有一个有效。

JS:

    $(".radio-type label").keydown(function (e) {
        // On Right Key press
        if (e.which == 39) {

            //Get the list of all buttons and labels
            var parentList = $(".radio-type").children();

            //Get index of currently focussed button
            var indexThis = $(this).index();

            //If not at the end of the list
            if (indexThis < parentList.length) {

                //Get the next in the list and its label
                var next = parentList.get(indexThis + 1);
                var nextLabel = parentList.get(indexThis + 2);

                $(next).change(); //Custom method that changes the selection

                //Remove the tab index from old and assign to nextLabel
                $(this).removeAttr("tabIndex");
                $(nextLabel).attr("tabIndex", "0");

                //Change the focus to the new selected label
                $(nextLabel).focus();
            }
        }
        e.preventDefault();
    });

编辑:HTML标记(名称已修改)

<div class="small-12 medium-12 large-4 columns radio-type @(!Model.ExtendedFilteringEnabled ? "medium-push-4" : "")">
    <input type="radio" name="tt" id="ttAll" value="@Model.CurrentBlock.TTAll" checked="checked" />
    <label for="ttAll" tabindex="0">All</label>
    <input type="radio" name="tt" id="tt1" value="@Model.CurrentBlock.TT1" />
    <label for="tt1">1</label>
    <input type="radio" name="tt" id="tt2" value="@Model.CurrentBlock.TT2" />
    <label for="tt2">2</label>
</div>

更新了Cory的jfiddle:http://jsfiddle.net/n99o3upp/10/(抱歉一直在弄错...)

2 个答案:

答案 0 :(得分:0)

我已经用一些东西更新了你的小提琴:

  • 更改了标记以便更轻松地进行DOM遍历。标签现在包含他们的输入。

  • 更改事件以触发输入而非标签

  • 将您的set方法更改为使用prop而不是attr,因为这将在DOM中设置实际值

  • if语句上进行比较,寻找一个小于length -1索引为0且长度为1的索引。

  • 通过定位而非显示使CSS隐藏输入。我在小提琴中对此进行了评论,以便您可以看到输入更改

  • 添加了e.preventDefault()以停止干扰您的js的默认浏览器操作

新的小提琴在这里:http://jsfiddle.net/n99o3upp/16/

但是,我不确定这些代码是否必要,因为没有它,浏览器无论如何都会做同样的事情。当DOM被标记为这样时,右键和左键会自动将焦点移动到组中的下一个输入。

我认为你可以删除keydown事件函数并离开change事件函数,这将完成您想要的相同操作。您可以通过在输入中向右移动然后向后移动来测试它。两者都有效,但右移是由你的脚本控制的,向左移动是自动的。

答案 1 :(得分:0)

我提出了一个粗略的解决方案,并不能解决所有情况。

我已经放弃了通过箭头键导航它的要求。所有标签上都有tabindex =“0”,因此可以使用空格或输入来标记它们。如果他们想要返回,默认的Shift + Tab可以做到这一点。

不幸的是,此解决方案无法在Chrome上运行,因为如果隐藏控件,浏览器的行为将无法让您专注于标签。