网页中有很多JS框架实现的事件模拟。
Is it possible to simulate key press events programmatically? 用于 jQuery
Javascript: simulate a click on a link 代表 YUI
然而,更简单的方法是 Ralf 给出的链接的第三篇文章,它关注关于表单元素内元素的 tabIndex 属性的“下一个”文本字段.
如果您制作一个文本字段的 ID 列表和您想要的顺序,可能会有更出色的方法。
当然,tabIndex 列表可能不是你自己生成的,而是在文本字段中走动生成的。
创建一个循环以在文档加载时生成列表(DOMContentLoaded):
var tabIndexList = new Array();
function tabIndexListGeneration(){
var form = document.getElementById("Your form ID"), // remember to fill in your form ID
textfields = form.getElementsByTagName("input"),
textfieldsLength = textfields.length;
for(var i=0;i<textfieldsLength;i++){
if(textfields[i].getAttribute("type") !== "text" || textfields[i].getAttribute("tabIndex") <= 0)continue;
/* tabIndex = 0 is neglected as it places the latest, if you want it, change 0 to -1
* and change tabIndexPointer = 0 into tabIndexPointer = -1 below */
tabIndexList[textfields[i].getAttribute("tabIndex")] = textfields[i];
}
}
// You can use the function of JS Framework if you don't like the method below.
if(document.addEventListener){
document.addEventListener("DOMContentLoaded", tabIndexListGeneration, false);
}else{
window.attachEvent("onload", tabIndexListGeneration);
}
并且在“文本输入等于文本字段最大长度”的事件中:
var tabIndexPointer = target.getAttribute("tabIndex"); // target is the DOM object of current textfield
while(!(++tabIndexPointer in tabIndexList)){
if(tabIndexPointer >= tabIndexList.length)
tabIndexPointer = 0; // or other action after all textfields were focused
}
tabIndexList[tabIndexPointer].focus(); // if other action needed, put it right after while ended
注意:表单文本字段的结构不能改变,否则会报错。
如果文本字段动态生成,请运行tabIndexListGeneration() 重新生成列表。