Hello World

document.write()를 언제 사용하시나요? 본문

Javascript/Tips

document.write()를 언제 사용하시나요?

EnterKey 2012. 9. 10. 19:18
반응형


Desktop.zip



1. document.write() 란 ?

- Writes a string into the document stream.

The open method opens the output stream for writing. When the document stream is opened, the write and writeln methods can be used to write some content into the document. If the document was opened by the open method, the close method must be used to close the output stream.


Note: while the document is loading, the document stream is opened for writing. In that case, there is no need to open and close the output stream.

After the document has been loaded, the open method (if at most two parameters are specified) clears the current document.


2. document.write() 의 몇가지 심각한 문제점에 대하여 먼저 알아보자


- document.write() does not work in XHTML


- document.write() executed after the page has finished loading will overwrite the page, 

   or write a new page, or not work


- document.write() executes where encountered: it cannot inject at a given node point


- document.write() is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem)


Far better to use the safe and DOM friendly DOM manipulation methods


즉, document.write() 함수를 사용하고 싶다면 문서가 초기화될 때 사용되어야 한다.


3. document.write()의 사용 시점은 

3.1 초기화가 이루워질 때 document.write사용하는 예

<HTML>

<HEAD>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<TITLE>방명록</TITLE>

</HEAD>

<BODY>

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript" >

var visitstr;

function TEXT_SEE() {

visitstr = document.FormText.TextStr.value;

document.write(" 글 :" + visitstr + "<br>");

}

</SCRIPT>

<P ALIGN="CENTER">

방명록을 남겨주세요

</P>

<FORM name="FormText">

<P ALIGN="CENTER">

<FONT SIZE="5" FACE="안상수2006가는">글쓰기</FONT>

<BR>

<TEXTAREA ROWS="15" COLS="50" ALIGN="CENTER" NAME="TextStr">여기에 글을 써주세요.</TEXTAREA>

<BR>

<INPUT TYPE="button" VALUE="확인" onClick="TEXT_SEE()">

<INPUT TYPE="RESET" VALUE="취소">

</FORM>

</BODY>

</HTML>



3.2 문서 초기화가 이루워진 이후, document.write() 보다는 innerHTML 의 사용이 적절하다.

<HTML>

<HEAD>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<TITLE>방명록</TITLE>

</HEAD>

<BODY>

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript" >

var visitstr;

function TEXT_SEE() {

visitstr = document.FormText.TextStr.value;

document.getElementById("txt").outerHTML = "<div> 글 :" + visitstr + "<br></div><div id='txt'></div>";

}

</SCRIPT>

<P ALIGN="CENTER">

방명록을 남겨주세요

</P>

<FORM name="FormText">

<P ALIGN="CENTER">

<FONT SIZE="5" FACE="안상수2006가는">글쓰기</FONT>

<BR>

<TEXTAREA ROWS="15" COLS="50" ALIGN="CENTER" NAME="TextStr">여기에 글을 써주세요.</TEXTAREA>

<BR>

<INPUT TYPE="Button" VALUE="확인" onClick="TEXT_SEE()">

<INPUT TYPE="RESET" VALUE="취소">

</FORM>

<div id="txt"></div>

<BR>

</FORM>

</BODY>

</HTML>


반응형
Comments