模拟TAB keydown:聚焦由'tabIndex`确定的下一个元素

Ran*_*lue 23 jquery

我有两个输入元素,第一个是聚焦的,我想通过模拟TAB keypress/keydown事件来关注第二个.(注意:我不想使用.next()或等.)

这是我的代码,灵感来自这个问题:

$('input').first().focus();

var e = $.Event('keydown');

e.which = 9; // TAB
$(':focus').trigger(e);
Run Code Online (Sandbox Code Playgroud)

请参阅http://jsfiddle.net/3PcPH/

代码不起作用.怎么了?

mVC*_*Chr 35

使用Javascript没有简单的编程方式来做到这一点...所以这是一种蛮力的方式.

根据W3:

应该获得焦点的元素应由用户代理根据以下规则进行导航:

  1. 首先导航那些支持tabindex属性并为其指定正值的元素.导航从具有最低tabindex值的元素继续到具有最高值的元素.值不必是顺序的,也不必以任何特定值开头.具有相同tabindex值的元素应按它们在字符流中出现的顺序进行导航.
  2. 接下来导航那些不支持tabindex属性或支持它并为其赋值"0"的元素.这些元素按它们在字符流中出现的顺序导航.
  3. 禁用的元素不参与Tab键顺序.

我通过以tabIndex > 0tabIndex顺序存储表单中的元素顺序,然后按照它们在文档中出现的顺序连接其余元素来完成此操作.下面的代码模拟了一个tab键,当你专注于表单输入并按下字母'z'时(但你可以将其更改为你需要的任何条件):

$(':input').keypress(function(e){ 

    // if 'z' pressed
    if (e.which == 122) {

        // if we haven't stored the tabbing order
        if (!this.form.tabOrder) {

            var els = this.form.elements,
                ti = [],
                rest = [];

            // store all focusable form elements with tabIndex > 0
            for (var i = 0, il = els.length; i < il; i++) {
                if (els[i].tabIndex > 0 &&
                    !els[i].disabled && 
                    !els[i].hidden && 
                    !els[i].readOnly &&
                    els[i].type !== 'hidden') {
                    ti.push(els[i]);
                }
            }

            // sort them by tabIndex order
            ti.sort(function(a,b){ return a.tabIndex - b.tabIndex; });

            // store the rest of the elements in order
            for (i = 0, il = els.length; i < il; i++) {
                if (els[i].tabIndex == 0 &&
                    !els[i].disabled && 
                    !els[i].hidden && 
                    !els[i].readOnly &&
                    els[i].type !== 'hidden') {
                    rest.push(els[i]);
                }
            }

            // store the full tabbing order
            this.form.tabOrder = ti.concat(rest);
        }

        // find the next element in the tabbing order and focus it
        // if the last element of the form then blur
        // (this can be changed to focus the next <form> if any)
        for (var j = 0, jl = this.form.tabOrder.length; j < jl; j++) {
            if (this === this.form.tabOrder[j]) {
                if (j+1 < jl) {
                    $(this.form.tabOrder[j+1]).focus();
                } else {
                    $(this).blur();
                }
            }
        }

    }

});
Run Code Online (Sandbox Code Playgroud)

见演示