我在将焦点设置在动态创建的输入元素上时遇到了问题,该输入元素之前已经丢失了焦点。我把它简化为这个简单的代码:
我希望您在键入时可以将焦点放在两个输入元素之间,但在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>
答案 0 :(得分:2)
首先,你应该使用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>