为select的option绑定键盘事件

1. 目的

  可以使用快捷键1、2、3、4等自动选中select框对应的option

2. 代码

<select id="selectItem" class="form-control">
    <option>北京</option>
    <option>上海</option>
    <option>广州</option>
    <option>深圳</option>
</select>
$("#selectItem").focus(function() {
    // 动态设置size支持option的事件监听
    this.size = this.children.length;
}).blur(function() {
    this.size = 1;
});

$("#selectItem option").click(function() {
    $("#selectItem option").each(function() {
        $(this).removeAttr("selected");
    });
    $(this).attr("selected", true);
    $("#selectItem").blur();
});

$(document).keydown(function(event) {
    var key = event.which; // 获取按键的ascii码
    var num = key - 48; // 获取对应的数字
    if (num >= 1 && num <= 4) { // 只有4个下拉框,只处理1-4
        var count = 1; // 计数
        $("#selectItem option").each(function() {
            if (count == num) {
                $("#selectItem").val($(this).text());
                $(this).attr("selected", true);
                $("#selectItem").blur();
            } else {
                $(this).removeAttr("selected");
            }
            count++;
        });
    }
});

 当select是动态生成的时候,绑定事件不生效,可以使用事件冒泡实现事件绑定

$("body").delegate("#selectItem", "focus", function() {
    this.size = this.children.length;
}).delegate("#selectItem", "blur", function() {
    this.size = 1;
}).delegate("#selectItem option", "click", function() {
    $("#selectItem option").each(function() {
        $(this).removeAttr("selected");
    });
    $(this).attr("selected", true);
    $("#selectItem").blur();
});

$(document).keydown(function(event) {
    var key = event.which; // 获取按键的ascii码
    var num = key - 48; // 获取对应的数字
    if (num >= 1 && num <= 4) { // 只有4个下拉框,只处理1-4
        var count = 1; // 计数
        $("#selectItem option").each(function() {
            if (count == num) {
                $("#selectItem").val($(this).text());
                $(this).attr("selected", true);
                $("#selectItem").blur();
            } else {
                $(this).removeAttr("selected");
            }
            count++;
        });
    }
});

 

posted @ 2018-04-09 10:11  禁忌夜色153  阅读(856)  评论(0编辑  收藏  举报