如何使$(this)选择器专注于当前元素?

How do you make the $(this) selector focus on current element?

本文关键字:专注 于当前 元素 选择器 何使 this      更新时间:2023-09-26

如何使$(this)选择器专注于当前元素?在这个示例中,我只在指定的元素中安装了它,所以你不能按enter键来激活你"在"的按钮。http://jsfiddle.net/mathzarro/gd6Ep/1/

这里是棘手的部分:$("button:first").trigger('focus');

p。我说我骑马是一种表达!最初的编码器是Ian,这里是链接…谢谢@Ian !http://jsfiddle.net/Vtn5Y/

真正的问题是由HazMat提到的,你专注于错误的元素(总是使用$("button:first").trigger('focus');的第一个按钮)。

在keydown处理程序结束时调用liSelected.trigger('focus');并删除对$("button:first").trigger('focus');的其他调用将解决问题。

你还有一个问题

$("button:eq(1)").click(function () {
    // Why are you calling this? Remove this line
    $("button:eq(0)").trigger('click');     
    update($("span:last"));
});

下面是一个工作示例

同样,jsfiddle很好,但是你也应该在这里发布相关代码。

改进建议

您发布的代码遭受脆弱的查询,内部耦合,也就是说,它不是很灵活地改变HTML结构。我重新编写了你的代码,使它的形状更好。以下是主要功能

  • 不坏如果你tab
  • 适用于您需要的尽可能多的按钮
  • 不硬编码第一个或最后一个div(智能换行)
  • 没有硬编码的输出div,所有处理在一个地方,依靠的事实,它是第n个按钮被点击。
  • 向上/向右移动向前,向下/向左移动向后
  • 不需要自己跟踪元素,这就是文档。activeElement用于
  • 每段代码是分开的
    • 为选定按钮添加类(仅CSS)(因此不需要为按钮添加"selected"类)
    • <
    • 更新输出/gh>
    • 设置下一个按钮的焦点

下面是代码

var buttons =  $('button');
var spans = $('span');
// Update the span when button is clicked
buttons.click(function(e){
    var span = $(spans[Array.prototype.indexOf.call(buttons, document.activeElement)]);
    span.text(parseInt(span.text(), 10) + 1);
});
// Handle the navigation, set focus on the next element
$(window).keydown(function(e){
    var isLeft = e.which === 38 || e.which === 37, 
        isRight = e.which === 40 || e.which === 39;
    if(isLeft || isRight){
        var currentButtonIndex =  Array.prototype.indexOf.call(buttons, document.activeElement);
        var nextButtonIndex;
        if (currentButtonIndex === -1) {
            nextButtonIndex = 0;
        } else {
            var toAdd = isLeft ? -1 : 1;
            nextButtonIndex = (currentButtonIndex + toAdd + buttons.length) % buttons.length;
        }
        buttons[nextButtonIndex].focus();
    }
});