메뉴 건너뛰기

2021.01.24 00:07

9장 실습문제 10번

조회 수 1204 댓글 2

<!DOCTYPE html>
<html>
<head>
    <title>계산기</title>
    <style type="text/css">
        #butn {width: 70px; padding: 10px}
        #txt {width: 280px; height: 20px;}
    </style>
    <script type="text/javascript">
        var first = 0;

        function back()
        {
            var len = txt.value.length;
            var backsp = txt.value.substring(0,len-1);

            txt.value = backsp;

        }
        function del()
        {
            txt.value="0";
            first=0;
        }
        function enter()
        {
            var exp = txt.value;
            txt.value=eval(exp);
        }
        function inp(obj)
        {    
            if(first==0) //초기 0 지우기
            {
                txt.value=""
            }
            first++;
            var clik = obj.value;
            var exp = txt.value;
            txt.value+= clik;
        }
    </script>
</head>
<body>
    <h3>계산기 만들기</h3>
    <hr>
    <form>
        <input id="txt" type="text" value="0">
    <br>
    <table>
        <tbody>
        <tr>
            <td><input id="butn" type="button" value="BACK" onclick="back()"></td>
            <td><input id="butn" type="button" value="CE" onclick="del()"></td>
            <td><input id="butn" type="button" value="C" onclick="del()"></td>
            <td><input id="butn" type="button" value="=" onclick="enter()"></td>
        </tr>
        <tr>
            <td><input id="butn" type="button" value="7" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="8" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="9" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="/" onclick="inp(this)"></td>
        </tr>
        <tr>
            <td><input id="butn" type="button" value="4" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="5" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="6" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="*" onclick="inp(this)"></td>
        </tr>
        <tr>
            <td><input id="butn" type="button" value="1" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="2" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="3" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="-" onclick="inp(this)"></td>
        </tr>
        <tr>
            <td><input id="butn" type="button" value="0" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="+" onclick="inp(this)"></td>
            <td><input id="butn" type="button" value="NONE"></td>
            <td><input id="butn" type="button" value="NONE"></td>
        </tr>
        </tbody>
    </table>
    </form>
</body>
</html>

9장 실습문제 10번에 대한 코드를 저렇게 짜봤는데 script 부분에 따로 var txt= document.getElementById("txt")를 하지않아도 작동하네요.. 오히려 저 getElement ... 를 넣으면 작동을 하지 않아요. 왜인가요...??

?
  • ?
    관리자 2021.01.24 10:13 Files첨부 (1)

    질문이 2가지네요. 한 가지 씩 알아봅시다.
    1. 먼저 var txt= document.getElementById("txt")를 사용하지 않아도 작동하는 이유?

    HTML4까지는 그냥 var txt= document.getElementById("txt") 코드를 사용하지 않고
    txt.value = "0"과 같이 그냥 txt를 사용하면 HTML 브라우저들이 id가 txt인 HTML엘리먼트로 처리하였습니다.
    하지만 HTML5에서는 이 방식은 표준이 아닙니다. 
    그럼에도 불구하고 HTML5 이전 시절에 작성된 웹페이지들을 위해 현재의 브라우저들이 
    txt.value = "0"과 같이 그냥 txt만 사용해도 처리해주고 있는 것 같습니다.
    앞으로 var txt= document.getElementById("txt")를 이용하는 것이 바람직합니다.

     

    2. var txt= document.getElementById("txt")를 넣으면 작동하지 않는다?
    현재의 코드에서 아래와 같은 위치에 넣으면 오류가 발생합니다.
    <script type="text/javascript">
            var first = 0;
            var txt= document.getElementById("txt"); // 이곳
    왜냐하면 이 코드가 실행되는 시점에서는 아직 <body> 이하 부분이 처리(파싱)되지 않아
    브라우저는 어떤 태그가 있는지 알 수 없기 때문입니다.
    그래서 이 문제를 해결하는 방법은 여러가지 가 있는데 다음과 같이 하면 됩니다.

    <script type="text/javascript">
            var first = 0;

    뒤에, HTML 페이지가 완전히 로딩된 후, txt= document.getElementById("txt"); 가 실행되도록

    window.onload를 달면 됩니다.

    몇가지 이유로, 첨부에 이미지로 넣었으니 참고하세요.

  • ?
    왜죠 ㅠㅠ 2021.01.24 23:28
    아하 알겠습니다!! 답변 감사합니다~!

QnA

공부하면서 궁금했던 것을 질문해보세요.

List of Articles
번호 제목 글쓴이 날짜 조회 수
공지 읽어주세요! 연습문제 및 실습문제 정답 공개에 관한 공지입니다. file 관리자 2017.06.20 18304
323 385p 8장 실습문제 07번 질문입니다. 1 12345 2019.08.16 617
322 코드 잘못된 부분을 봐주시면 정말 감사하겠습니다 1 file 입문한 사람 2020.04.01 608
321 7장 실습문제 1번 질문 있습니다. 7 jonjsin 2017.11.09 604
320 timerID값이 null인 이유 1 열공이 2022.05.26 602
319 저자님 367페이지 질문있습니다~~ 1 file 칼잡이최제잘 2018.02.19 592
318 6장 7번 좀 알려주세요 ㅜㅜ 1 어려워여 2020.06.14 590
317 9장 onblur onfocus 활용 실습문제 2번 웹린이 2018.05.21 569
316 4장 6번문제 물어볼려고합니다 1 배재한 2019.04.16 566
315 5장 실습문제 9번 1 file 123 2018.10.03 563
314 교과서 13장 연습문제 1 알고싶어요 2021.05.29 553
313 9장 4번 질문있습니다. 웹프로그래밍 2017.05.28 551
312 이미지를 HTML 파일과 같은 폴더에 저장하였는데 왜 이미지가 보이지 않을까요? 1 황기태 2017.03.27 547
311 바닐라js 란 것에 대해 질문이 있습니다. 2 muuum 2018.11.01 546
310 1장 test1, 2, 3 파일 2 열공중 2020.03.07 542
309 간단한 질문 드립니다. 1 뚜룹 2018.06.07 535
308 이 책을 다 본 뒤 어떤 공부를 더 하는게 좋을까요? 1 file muuum 2018.10.31 526
307 8장 실습문제 8번 질문드립니다. 3 메론 2018.11.11 525
306 명품 HTML5+ 수정판 2장 4번 문제 문의 1 file mikael 2021.04.14 520
305 HTML5+CSS3+Javascript 웹 프로그래밍[수정판] 4 file Jenny 2021.09.25 519
304 오픈 챌린지 6장 1 ㄱㄷㄱㄷ 2018.04.22 514
목록
Board Pagination Prev 1 ... 2 3 4 5 6 7 8 9 10 ... 21 Next
/ 21
위로