jQuery:如何从一个td导航到表中的特定其他td

时间:2015-06-03 17:48:30

标签: javascript jquery html arrow-keys

我是jQuery的新手,所以我可能会以错误的方式处理这个问题,但希望有人可以帮助我。

我有一个动态创建的非常大的HTML表。 为了帮助用户我只想为此表将导航事件绑定到箭头键。 在这个例子中,我想

从div跳转到下一个div (他们也有类"myClass")。该表比下面的示例大,但结构总是重复,所以每三个td都有一个(可编辑的)div。

到目前为止,我无法让这个工作,但功能确实抓住箭头按下,因为我可以这样显示警报。

我的jQuery:

$(document).on('keydown', '#tblCalendar', function(e){
    switch(e.which) {
        case 37: // left
            // similar action to the left
            break;                  
        case 39: // right
            $(this).closest('td').next().next().next().find('div').focus();
            break;          
        default: return; // exit handler
    }
    e.preventDefault(); // prevent default action
});

我的HTML(简化):

<tbody>
    <tr>
        <td></td>
        <td></td>
        <td><div class="myClass"></div></td>
        <td></td>
        <td></td>
        <td><div class="myClass"></div></td>
        // ...
    </tr>
    // ...
</tbody>

非常感谢, 麦克

2 个答案:

答案 0 :(得分:1)

您应该使用nextUntil查找其中包含td的下一个div

$(this).closest('td').nextUntil("td div").focus();

虽然我不确定div如何获得focus

由于this指的是整个表格,因此请更改处理程序以观察可信任的div

上的按键
$(document).on('keydown', '#tblCalendar tr td div', function(e){

答案 1 :(得分:1)

我稍微重建了你的功能。现在它只涉及一个DOM请求来收集所有可编辑元素并将它们存储在变量中。您可以使用箭头键旋转所有这些。如果没有选择任何元素,它将获得第一个元素。我已经为demonstrate that behavior添加了一个课程。要根据您的需要进行调整,只需将.addClass('active')替换为.get(0).focus()

具有切换类

的主体示例
var focusable = $('div.myClass');
var current = null;

$(document).on('keydown', function(event) {
    var next = null;

    if (37 == event.which || 39 == event.which) {
        if (null == current) {
            current = 0;
            focusable.eq(current).addClass('active');
            return;
        }

        if (37 == event.which) {
            next = current - 1;
            if (0 > next) {
                next = focusable.length - 1;
            }
        }

        if (39 == event.which) {
            next = current + 1;
            if (focusable.length == next) {
                next = 0;
            }
        }

        focusable.eq(current).removeClass('active');
        focusable.eq(next).addClass('active');
        current = next;
    }
});

在没有涉及类切换的情况下减少代码

var focusable = $('div.myClass');
var current = null;

$(document).on('keydown', function(event) {
    if (37 == event.which || 39 == event.which) {
        if (null == current) {
            current = 0;
            focusable.eq(current).get(0).focus();
            return;
        }

        if (37 == event.which) {
            --current;
            if (0 > current) {
                current = focusable.length - 1;
            }
        }

        if (39 == event.which) {
            ++current;
            if (focusable.length == current) {
                current = 0;
            }
        }

        focusable.eq(current).get(0).focus();
    }
});

<强>演示

Try before buy
Try before buy with focusable divs