2012-04-02 27 views
0

その場で作成された入力要素にフォーカスを設定する際に問題があります。プログラムで入力要素にフォーカスを設定する

入力時に2つの入力要素の間にping-pongに焦点を当てますが、FirefoxとChromeでは、2番目のテキストボックスが作成された後に最初のテキストボックスにフォーカスがとどまりますフォーカスを受け取り、最初のフォーカスにフォーカスを戻しました。どうしてこれなの?

<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> 

答えて

2

まず、jQueryを使用する必要があります。

フィールドbを作成するときに、フィールドcを追加するときに、+ =演算子とinnerHTMLを組み合わせて使用​​すると、以前フィールド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> 
+0

ありがとうございました!いったん私の間違いを明らかにしたら、追加したいinnerHTMLで要素を作成し、それを表示するためにcontainer.appendElement(new)を使用するようにコードを適合させるのは簡単でした。 – Will

関連する問題