将焦点设置在以编程方式创建的输入元素上

setting focus on input element created programmatically

本文关键字:创建 输入 元素 方式 编程 焦点 设置      更新时间:2023-09-26

我在设置一个动态创建的输入元素的焦点时遇到问题,该元素以前有焦点也有焦点丢失。我把它提炼成了一个简单的代码:

我希望焦点在您键入时在两个输入元素之间来回切换,但在Firefox和Chrome上,在创建第二个文本框、接收焦点并将焦点发送回第一个文本框后,焦点会停留在第一个文本盒中。为什么会这样?

<html>
<head>
<script type="text/javascript">
<!--
function onkey(event) {
    if(event.target.id == "b") {
        var c = document.getElementById("c");
        if(!c) {
            document.getElementById("a").innerHTML += "<br/><input id='"c'" type='"text'"/>";
            c = document.getElementById("c");
            document.getElementById("status").textContent = "created c "+c
        } else {
            document.getElementById("status").textContent = "activing c "+c;
        }
        c.onkeydown = onkey;
        c.focus();
    } else {
        document.getElementById("status").textContent = "activing b";
        document.getElementById("b").focus();
    }
}
function test() {
    var b = document.getElementById("b");
    b.onkeydown = onkey;
    b.focus();
}
//-->
</script>
<body onload="test();">
<noscript>
Sorry, you need javascript.  Not much to see here otherwise; move along.
</noscript>
<div id="status"></div>
<div id="a">
<input id="b" type="text"/>
</div>
</body>
</html>

首先,您应该使用jQuery。

当您通过使用+=运算符和innerHTML添加字段c时,您正在重新创建输入字段b,从而有效地破坏了您之前在字段b上创建的事件。

下面的代码将解决您的问题,但您绝对应该为此使用jQuery。

<html>
<head>
<script type="text/javascript">
<!--
function onkey(event) {
    console.log(event.target.id);
    if(event.target.id == "b") {
        var c = document.getElementById("c");
        if(!c) {
            // here you reset all html within the a tag, destroying ALL events
            document.getElementById("a").innerHTML += "<br/><input id='"c'" type='"text'"/>";
            c = document.getElementById("c");
            // rebinding the event to b will fix the issue 
            document.getElementById("b").onkeydown = onkey;
            document.getElementById("status").textContent = "created c ";
        } else {
            document.getElementById("status").textContent = "activating c ";
        }
        c.onkeydown = onkey;
        c.focus();
    } else {
        document.getElementById("status").textContent = "activating b";
        document.getElementById("b").focus();
    }
}
function test() {
    var b = document.getElementById("b");
    b.onkeydown = onkey;
    b.focus();
}
//-->
</script>
<body onload="test();">
<noscript>
Sorry, you need javascript.  Not much to see here otherwise; move along.
</noscript>
<div id="status"></div>
<div id="a">
<input id="b" type="text"/>b
</div>
</body>
</html>