Javascript 在添加的每个新文本输入上添加焦点

Javascript 在添加的每个新文本输入上添加焦点,javascript,jquery,Javascript,Jquery,我使用我发现的这个脚本在用户单击文本链接时添加一个文本框,我有没有办法使每个自动出现的新文本框都有光标在文本框内 下面是脚本: function add(orderType) { //Create an input type dynamically. var element = document.createElement("input"); //Assign different attributes to the element. element.setAttribute("type", "

我使用我发现的这个脚本在用户单击文本链接时添加一个文本框,我有没有办法使每个自动出现的新文本框都有光标在文本框内

下面是脚本:

function add(orderType) {

//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("name", orderType + "[]");


var foo = document.getElementById(orderType);

//Append the element in page (in span).
//Create the option text
var a = document.createTextNode("Choice: ");
foo.appendChild(a);
foo.appendChild(element);
var br = document.createElement("br");
foo.appendChild(br);
i++;    
}
非常感谢将
元素添加到
foo
后调用
元素.focus()

function add(orderType) {
    //Create an input type dynamically.
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", "text");
    element.setAttribute("name", orderType + "[]");


    var foo = document.getElementById(orderType);

    //Append the element in page (in span).
    //Create the option text
    var a = document.createTextNode("Choice: ");
    foo.appendChild(a);
    foo.appendChild(element);
    var br = document.createElement("br");
    foo.appendChild(br);

    element.focus();//focus new input

    i++;
}

jQuery解决方案将选择最后一个输入,然后对其进行聚焦,其中#ordertype是容器id:

$(“#”+orderType+“输入:上次”).focus()


我用javascript编程已经有一段时间了,现在重新学习它。。。我相信,。专注是你想要的

document.getElementById(orderType).focus 
=====================

.tabindex((希望正确的syntex))与“tab”键一起使用

更多用于注册页面或填写配送地址页面。您只是简单地设置了tabindex,所以当您按tab键时,它会将您带到文档上下一个最高的tabindex编号。当页面通过javascript动态更改时,它会更有用

==================

在我的脑海里,我想说还有一个

.something
document.getElementById(orderType).something
for <input /> or <input></input> or like elements 
什么 document.getElementById(orderType) 用于或类似元素

但我现在记不起来了。这涉及到“游标”,但它可能是一个跨浏览器的脚本。而且只在一种主流浏览器中实现

element.focus()
foo.appendChild
@megawac之后的结尾处-不错!工作得很好。抱歉,stackoverflow自动添加了jquery,我不能100%确定它是什么。不完全是,
orderType
是一个变量id。应该是
$(“#”+orderType+“输入:最后一个”)
.something
document.getElementById(orderType).something
for <input /> or <input></input> or like elements