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++;
            });
        }
    });
  • 相关阅读:
    CRM详细介绍网址
    element上传多图片
    多图片上传WebForm
    MemCached原理
    Redis的原理
    Ninject用法详解
    SQLsugar和unity 的用法
    json中的转义字符的处理
    fiddler
    orm多表关系
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/8757715.html
Copyright © 2011-2022 走看看