我想将导航键从tab键切换到Enter键。为此我勾选了像
这样的形式的按键事件$("form").live("keypress", function (e) {
if (e.keyCode == 13) {
//here should come the code for finding next element and focusing it
return false; // this line prevents submission of form on enter key
}
在这个函数中,我只需找到下一个表单元素并将焦点转移到那个元素上。为了获得下一个表单元素,我使用了answer中的选择器。但它有几个问题:
除此之外,它使用输入的索引属性来查找下一个元素,但问题是当我用索引警告所有表单元素时。它们并不是唯一的。
$('form input,form select').each(function (ind, elem) {
alert($(elem).attr("name"));
alert($(elem).index());
});
有许多带有0索引的表单元素。值得注意的是,一些表单元素使用JavaScript插入DOM,即页面加载后。我怎么解决这个问题?
答案 0 :(得分:0)
这样的东西?您可能需要修改isFocusableInput
功能以获得所需的效果。我已经离开了console.log
,所以你可以看到发生了什么。
$("form").live("keypress", function (e) {
function isFocusableInput(el) {
// TODO - e.g.
var $el = $(el);
var typeOk = !el.type || !el.type.match(/^(hidden)$/);
return $el.is(":visible") && typeOk && !$el.is('[readonly]') && !$el.is('[disabled]');
}
function findFocusableInput($form, $input) {
var inputs = $form.find(":input");
console.log(inputs);
var thisIdx = inputs.index($input);
console.log("thisIdx=" + thisIdx);
var count = 0;
var input = null;
// -1 because we don't want to focus the original element
while (++count < inputs.length-1) {
var i = (thisIdx+count)%inputs.length;
input = inputs.eq(i)[0];
console.log(i + "," + input.tagName);
console.log(input);
if (isFocusableInput(input)) {
return input;
}
}
return null;
}
var $input = $(e.target);
var $form = $(this);
console.log($input);
console.log($form);
if (e.keyCode == 13) {
e.stopPropagation();
var focusableInput = findFocusableInput($form, $input);
console.log(focusableInput);
if (focusableInput) {
focusableInput.focus();
}
return false;
}
});
答案 1 :(得分:0)
我能够使用以下代码完成此任务
$("form").live("keypress", function (e) {
if (e.keyCode == 13) {
var $fomrElements = $('form input,form select').not(":hidden").not(":disabled");
var $nextIndex = $fomrElements.index(e.target) + 1;
var $nextInput = $fomrElements.eq($nextIndex);
$nextInput.focus();
return false;
}
});