2

我有一个多项选择题列表:

<div class="question active">
    <p>The first counting tool was the _____.</p>
    <button class="btn-a">A) Stepped Reckoned</button>
    <button class="btn-b">B) Abacus</button>
    <button class="btn-c">C) Aba Zaba</button>
    <button class="btn-d">D) Punch Card</button>
</div>
<div class="question">
    <p>Who founded IBM and was responsible for tabulating the US Census with a punch card tabulator in only six weeks?</p>
    <button class="btn-a">A) Jacquard</button>
    <button class="btn-b">B) Hollerith</button>
    <button class="btn-c">C) Mark I</button>
    <button class="btn-d">D) Babbage</button>
</div>

如何触发这些按钮中的每一个以在键盘上提交相应的字母?

键盘只能处理.active问题。


奖金:

是否可以允许两个键触发问题?例如,由于ABCD在键盘周围隔开,因此允许QWERJKL;对应以ABCD使其易于单手键盘输入也可能是有帮助的。

4

1 回答 1

1

使用该keyup事件,您可以监听用户释放键。然后,您可以将其翻译成字母(或箭头键,在我的示例中),并访问相应的问题/按钮。你可以尝试这样的事情:

$(document).ready(function () {
    var $questions = $("div.question"),
        $activeQuestion = function () {
            return $questions.filter(".active");
        },
        $prevQuestion = function (setActive) {
            var $prev;
            $prev = $activeQuestion().prevAll(".question").first();
            if ($prev.length === 0) {
                $prev = $questions.last();
            }
            return $prev;
        },
        $nextQuestion = function () {
            var $next;
            $next = $activeQuestion().nextAll(".question").first();
            if ($next.length === 0) {
                $next = $questions.first();
            }
            return $next;
        };

    $(document).on("keyup", function (e) {
        var key, character, $active, $next, $prev;
        key = e.which;
        switch (key) {
            case 37:
            case 38:
                $prev = $prevQuestion();
                $questions.removeClass("active");
                $prev.addClass("active");
                break;
            case 39:
            case 40:
                $next = $nextQuestion();
                $questions.removeClass("active");
                $next.addClass("active");
                break;
            default:
                character = String.fromCharCode(key).toLowerCase();
                $active = $activeQuestion();
                $active.find("button").removeClass("selected").filter(".btn-" + character).addClass("selected");
                break;
        }
    });
});

演示:http: //jsfiddle.net/wdXkB/1/

我走得有点远,但我添加了使用箭头键移动到下一个问题(向下和向右箭头)或上一个问题(向上和向左箭头)的功能。

于 2013-07-23T16:29:15.290 回答