jQuery查找下一个表单元素以进行导航(一些字段动态添加到表单中)
我想将导航从tab键切换到Enter键。为此,我钩住了如下形式的按键事件jQuery查找下一个表单元素以进行导航(一些字段动态添加到表单中),jquery,jquery-selectors,navigation,Jquery,Jquery Selectors,Navigation,我想将导航从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").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
}
在这个函数中,我只需要找到下一个表单元素并将焦点转移到那个元素上。为了得到下一个表单元素,我使用了这个选择器。但它有两个问题:
$('form input,form select').each(function (ind, elem) {
alert($(elem).attr("name"));
alert($(elem).index());
});
有许多索引为0的表单元素。值得注意的是,一些表单元素是在页面加载之后使用JavaScript插入DOM的。我怎样才能解决这个问题 像这样的?您可能需要修改
isFocusableInput
函数以获得所需的效果。我已将控制台保留。登录以便您可以查看发生了什么
$("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;
}
});
$(“表单”).live(“按键”,功能(e){
函数isFocusableInput(el){
//待办事项-例如。
变量$el=$(el);
var typeOk=!el.type | |!el.type.match(/^(隐藏)$/);
返回$el.is(“:visible”)&&typeOk&&!$el.is(“[readonly]”)和&!$el.is(“[disabled]”);
}
函数findFocusableInput($form,$input){
变量输入=$form.find(“:input”);
控制台日志(输入);
var thisIdx=输入。索引($input);
console.log(“thisIdx=“+thisIdx”);
var计数=0;
var输入=null;
//-1因为我们不想聚焦原始元素
而(++计数
我能够使用以下代码完成此任务
$("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;
}
});
您没有正确使用index()
$(elem).index()
在您的情况下将始终返回0。在我看来,您不应该因为可访问性的原因而覆盖默认浏览器行为。Alex您是对的,当焦点以编程方式移动时,某些元素没有触发更改事件