How do you make the $(this) selector focus on curr

2019-09-15 12:48发布

How do you make the $(this) selector focus on current element? In this jsfiddle, I've mounted it only goes in a specified element, so you cant press enter to activate the button you 'are in'. http://jsfiddle.net/mathzarro/gd6Ep/1/

Heres the tricky part: $("button:first").trigger('focus');

Ps. I've said I mounted as an expression! The original coder was Ian, here it is the link.. thanks @Ian! http://jsfiddle.net/Vtn5Y/

1条回答
叛逆
2楼-- · 2019-09-15 12:55

The real problem was mentioned by HazMat, you were focusing on the wrong element (always the first button using $("button:first").trigger('focus');.

Calling liSelected.trigger('focus'); at the end of your keydown handler and removing the other calls to $("button:first").trigger('focus'); will fix the problem.

You also have another problem

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

Here's a working example

Also, the jsfiddle is great but you should post the code relevant code here too.

Improvement suggestion

The code you posted suffers from brittle queries, internal coupling, that is, it's not very flexible to changing HTML structures. I've re-worked your code so that it's in better shape. Here are the main features

  • Doesn't break if you tab
  • Works for as many buttons as you need
  • No hardcoding for first or last div (smart wrap around)
  • No hardcoding of the output divs, all handled in one place, by relying on the fact that it's the nth button being clicked.
  • Up/right go forwards, down/left go backwards
  • No need to track the element yourself, that's what document.activeElement is for
  • Each section of code is separated
    • Add class to selected button (CSS only) (so it doesn't need to add a "selected" class to buttons.
    • Update output
    • Set focus on the next buttons

Here's the code

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();
    }
});
查看更多
登录 后发表回答