2010-05-05 4 views
0

HTML과 JavaScript로 실험하고 있습니다. 흰색 페이지만을 남기지 않고, 키 입력을 입력 할 때 텍스트 상자가 사라지면 어떤 이유이벤트 핸들러에서 document.write 사용?

<html> 
    <body> 
     <input type="text" id="commandInput" name="command" size="50" /> 
     <script type="text/javascript"> 
      var commandInput = document.getElementById("commandInput"); 
      commandInput.onkeydown = function (evt) { 
       document.writeln("Test"); 
      }; 
     </script>  

    </body> 
</html> 

: 텍스트 상자에 키 입력을 입력 할 때 다음 코드는 뭔가를 인쇄해야합니다.

왜 이런 생각입니까?

답변

3

페이지가로드 된 후 document.write 또는를 사용하지 마십시오. 페이지가로드 된 후이를 호출하면 (Firefox에서는 적어도) 현재 문서를 삭제하는 document.open()이라는 자동 호출이 수행됩니다.

디버깅 도구로 사용하는 경우 Firebug 및 console.log()을 대신 사용하시기 바랍니다.

3

.innerHTML을 사용하여 요소에 텍스트를 삽입하는 대체 방법이 있습니다.

<html> 
    <body> 
     <input type="text" id="commandInput" name="command" size="50" /> 
     <div id="text"></div> 
     <script type="text/javascript"> 
      var commandInput = document.getElementById("commandInput"); 
      commandInput.onkeydown = function() { 
       document.getElementById("text").innerHTML="Testing..."; 
      }; 
     </script>  
    </body> 
</html> 
0

최신 입력을 새로운 입력란으로 가져 오려면 대신 onkeyup을 사용해보십시오.

사이드 바에서 이것을 new.html에 던져보고 확인해보십시오. 그냥 멋지다면 멋지게 보일 것입니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>onkeyup</title> 
<script type="text/javascript"> 
    function setFocus(){ 
     document.theForm.command.focus(); 
    } 
</script> 
</head> 

<body onload="setFocus()"> 
<form id="theForm"> 
<input type="text" id="commandInput" name="command" size="50" style="font-size:20px; color:gray; font-family:arial; border:0 none; opacity:0.4" /> 
     <div id="text" style="position:absolute; float:left; margin-left:3px; margin-top:-26px; font-size:20px; font-family:arial; color:black;"></div> 
     <script type="text/javascript"> 
      var commandInput = document.getElementById("commandInput"); 
      commandInput.onkeyup = function() { 
       document.getElementById("text").innerHTML=commandInput.value; 
      }; 
     </script> 
</form> 
</body> 
</html> 

페이지를로드 할 때 Tab 키를 누르고 입력을 시작하십시오.

관련 문제