• 为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++;
            });
        }
    });
  • 相关阅读:
    CUBRID学习笔记 41 sql语法之select
    CUBRID学习笔记 40 使用net修改数据
    CUBRID学习笔记 39 net使用dataset 返回查询的数据
    CUBRID学习笔记 38 net调用java的函数过程
    CUBRID学习笔记 36 在net中添加多行记录
    CUBRID学习笔记 37 ADO.NET Schema Provider
    CUBRID学习笔记 35 net驱动错误码和信息 cubrid教程示例
    程序员应该关注的一些事儿
    如何区分一个程序员是“老手“还是“新手“?
    10个调试和排错的小建议
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/8757715.html
Copyright © 2020-2023  润新知