zoukankan      html  css  js  c++  java
  • 为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++;
            });
        }
    });
  • 相关阅读:
    重链剖分的总结与模板
    PBDS学习笔记(一)
    LCT 第一题 洛谷模板
    2018年暑假第四次周赛-图论部分题解
    后缀数组求不同子串的个数
    Codeforces Round #106 (Div. 2) Coloring Brackets(区间DP)
    Codeforces Round #510 (Div. 2) D. Petya and Array (权值线段树)
    HDU 3974 Assign the task (dfs序+线段树)
    Manthan, Codefest 18 (rated, Div. 1 + Div. 2) D.Valid BFS? (模拟)
    POJ
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/8757715.html
Copyright © 2011-2022 走看看