如何使用键盘在jquery ui选项卡中导航

时间:2013-12-24 13:10:21

标签: jquery html jquery-ui jquery-tabs

我正在为标签实现jquery功能。选项卡一包含文本框。填写文本框后。当用户使用键盘移动到下一个选项卡时,按Tab键后将转到下一个选项卡。我写了下面的代码,但我没有得到输出。我做错了什么?

这是我的j查询脚本

$(document).ready(function () {
    $("#tabs").tabs();
    $("body").keyup(function (e) {
        var direction = null;
        if (e.keyCode == 37) {
            direction = 'prev';
        }
        if (e.keyCode == 39 || e.keyCode == 9) {
            alert("test"); //direction='next';
        }
        if (direction != null) {
            var totaltabs = $('#tabs').tabs('length'); //gettting the total # of tabs
            var selected = $('#tabs').tabs('option', 'selected'); //getting the currently selected tab
            if (direction == 'next') {
                if (selected <= totaltabs - 1)
                    $('#tabs').tabs('select', selected + 1)
            } else {
                if (selected != 0)
                    $('#tabs').tabs('select', selected - 1)
            }
        }
    });
});

这是我的HTML代码

<div id="tabs">
    <ul class="tabNavigation">
        <li><a href="#first">tab-1</a>
        </li>
        <li><a href="#second">tab-2</a>
        </li>
        <li><a href="#third">tab-3</a>
        </li>
    </ul>
    <div id="first">First name:
        <input type="text" name="fname">
        <br>
        <br>Last name:
        <input type="text" name="lname">
        <br>
    </div>
    <div id="second">City 1:
        <input type="text" name="city1">
        <br>
        <br>City 2:
        <input type="text" name="city2">
        <br>
    </div>
    <div id="third">
        <p>tab 3</p>
    </div>
</div>

谢谢

1 个答案:

答案 0 :(得分:2)

$(document).ready(function () {
    $("#tabs").tabs({
        activate: function(event, ui) {
            ui.newPanel.find('input').eq(0).focus();
        }
    });

    $("#tabs .ui-tabs-panel").each(function() {
        $(this).find('input').last().on('keydown', function(e) {
            var totaltabs = $('#tabs').tabs('length');
            var selected = $('#tabs').tabs('option', 'selected');

            if(e.keyCode === 9 && !e.shiftKey) {
                selected = (selected + 1) % totaltabs;
                $('#tabs').tabs('select', selected);
                return false;
            }
        });

        $(this).find('input').first().on('keydown', function(e) {
            var totaltabs = $('#tabs').tabs('length');
            var selected = $('#tabs').tabs('option', 'selected');

            if(e.keyCode === 9 && e.shiftKey) {
                selected = selected - 1 > -1 ? selected - 1 : totaltabs - 1;
                $('#tabs').tabs('select', selected);
                return false;
            }
        });
    });
});