我有一个将“Enter”转换为“Tab”的脚本,它在我点击表单上的隐藏字段之前效果很好.
那么,有没有办法检测隐藏字段,仍然使用脚本(在IE& firefox中)?
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i]) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
最佳答案 将代码更改为如下所示:
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i] && $(ele[q]).is(":visible")) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
我刚添加了一个检查,以确保您要聚焦的元素是可见的(未隐藏).
编辑:如果要完全跳过隐藏字段,请使用以下代码.
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
var self = $(obj),
form = self.parents('form:eq(0)'),
focusable, next;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(obj) + 1);
if (!next.length) {
next = focusable.first();
}
next.focus();
return false;
}
}
小提琴:
https://jsfiddle.net/mwatz122/0zqzzmc1/