将焦点设置为以编程方式创建的输入元素
问题描述:
我在将输入元素设置为焦点时出现问题,这些输入元素是在运行中创建的,以前已经失去焦点的输入元素。我已经将它简化为以下简单的代码:将焦点设置为以编程方式创建的输入元素
我希望在您键入时,重点在两个输入元素之间进行乒乓,但在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>
谢谢!一旦你显示我的明显错误,很容易调整代码以创建一个元素,并添加我想要添加的innerHTML,然后使用container.appendElement(new)来显示它。 – Will 2012-04-02 10:25:52