65.9K
CodeProject 正在变化。 阅读更多。
Home

使用Tab键选择ASP.NET下拉列表项

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2012年7月1日

CPOL

3分钟阅读

viewsIcon

34038

使用 jQuery 插件选择下拉列表项。

select item in drop-down list using tab key

目录

引言

几天前,我看到CodeProject一位成员发帖询问类似“如何使用Tab键选择下拉列表中的数据”的问题。我猜他指的是如何使用键盘Tab键选择下拉列表中的项目。通常,我们可以使用上下箭头键从高亮显示的下拉列表中选择项目。我进行了谷歌搜索,但没有找到太多相关信息,而且我觉得这个问题很有趣。因此,我决定使用jQuery来实现解决方法。示例代码已附加,欢迎大家下载。

实现

清单1-3简要总结了插件,并在每一行都包含注释。Tab键的键码是9。默认情况下,按下Tab键会导致光标移到下一个控件。我们可以使用`event.preventDefault()`方法来阻止元素的默认操作。现在,当用户按下Tab键时,下拉列表中的项目将切换焦点到列表中的下一个项目。基本上,下一个选定索引等于当前选定索引加一。为了去除空白下拉列表(图1),当选择到达最后一项时,将选定索引设置为`0`。

列表 1

//Tab key pressed
if (keyCode == 9) {
    e.preventDefault();
    //increase the selected index by 1 and set selected to the new index
    $this.prop('selectedIndex', parseInt(curSelItemIndex) + 1);
    //if selected index == number of items
    //  set the selected index=0
    if (curSelItemIndex == items - 1) {
        $this.prop('selectedIndex', 0);
    }
}
图 1

drop-down list first item blank

接下来的任务是从选定的下拉列表中移除焦点,并在按下Esc键时将焦点设置到下一个控件。我们可以使用jQuery的`blur()`函数从高亮显示的下拉列表中移除焦点。之后,搜索选定下拉列表对象中的下一个第一个元素,并将焦点设置到该元素。

列表 2

//Escape key pressed
if (keyCode == 27) {
    e.preventDefault();
    // remove the focus from the selected dropdownlist and
    $this.blur();
    // move the focus on selected control to the next control
    jQuery(":input:eq(" + (jQuery(":input").index($this) + 1) + ")").focus();
    return;
}

最后一步是确保按下**Shift** + **Tab**键会将焦点返回到上一个控件。请参考清单3。

列表 3

//Shift + Tab Key
if (keyCode == 9 && e.shiftKey) {
    e.preventDefault();
    // remove the focus from the selected dropdownlist and
    $this.blur();
    // move the focus on selected control to the previous control
    jQuery(":input:eq(" + (jQuery(":input").index($this) - 1) + ")").focus();
    return;
}

Using the Code

包含jQuery库和插件,以及您想要的任意数量的下拉列表控件/元素到网页中。请参考清单4了解如何调用插件。

列表 4

<script type="text/javascript">
        $(document).ready(function () {
            $("[id$='DropDownList1']").myDDLPlugin();
            $("[id$='DropDownList3']").myDDLPlugin();
            $("[id$='DropDownList5']").myDDLPlugin();
        });
    </script>

看点

有一段时间,我一直卡在试图找到一个解决方案,以便在具有跨浏览器兼容性的情况下将焦点移动到前一个和下一个控件。后来,我在http://stackoverflow.com上找到了解决方法。由于某种原因,以下代码在页面上没有任何输入标签的情况下也能正常工作。代码清楚地表明它应该查找下一个输入元素。无论如何,我已经在HTML和ASP.NET页面上对其进行了测试,并且运行良好。

清单5

jQuery(":input:eq(" + (jQuery(":input").index($this) + 1) + ")").focus(); //next
jQuery(":input:eq(" + (jQuery(":input").index($this) - 1) + ")").focus(); //previous

我认为这个插件对于内部数据录入Web应用程序可能非常有用。

结论

我希望有人会发现这些信息有用,并让你的编程工作更容易。如果你发现任何错误或不同意内容,或者想帮助改进这篇文章,请给我留言,我会和你一起改正。我建议下载演示并探索它,以便充分理解其概念,因为我可能在这篇文章中遗漏了一些重要信息。如果你想帮助改进这篇文章,请发邮件给我。

测试环境:Internet Explorer 9.0,Firefox 12.0,Google Chrome 19.0,Apple Safari 4.0.4

browsers

历史

  • 2012年6月30日:初始版本

资源

观看脚本运行

下载

© . All rights reserved.