본문 바로가기
괴발개발/js

데이터 입출력

by 맛길만걷자 2024. 6. 13.
728x90
반응형

javascript

function btnAlert(){
    window.alert("alert 버튼 클릭 됨");
    // window는 브라우저 자체를 나타내는 객체
    // -> JS 코드는 브라우저(window) 내부에서 실행되는 코드이다보니
    // window를 생략할 수 있다.
}

// document.write 확인
function documentWrite(){
   // document.write("내용");
   //document.write("<b>이제 곧</b><br><h3>쉬는 시간</h3>");
  // 출력할 문구에 html 태그가 있을 경우 해석해서 시각적인 요소로 보여짐

  let a = "<table border='1'>";
  a += "<tr>";
  a += "<td>1</td>";
  a += "<td>2</td>";
  a += "</tr></table>";

  document.write(a);

}

// innerText 읽어오기
function getInnerText(){
    // HTML 문서 내에서 아이디가 "test1"인 요소를 얻어와
    // test1 변수에 대입

    const test1 = document.getElementById("test1");

    // test1 변수에 대입된 요소에서 내용을 얻어와 console에 출력

    console.log(test1.innerText);

}

// innerText 변경하기
function setInnerText(){
    // id가 "test1"인 요소를 얻어와
    // test1변수에 대입
    const test1 = document.getElementById("test1");

    // test1 변수에 새로운 내용을 작성해서 대입

    test1.innerText = "innerText로<br> 변경된 내용입니다.";
}

// innerHTML로 읽어오기
function getInnerHTML1(){
    const test2 = document.getElementById("test2");
    console.log(test2.innerHTML);
}

// innerHTML로 변경하기
function setInnerHTML1(){
    const test2 = document.getElementById("test2");
    test2.innerHTML = "innerHTML로<br> <b>변경된 내용입니다.</b>";

}

// innerHTML 응용
function add(){
    // 1) 아이디가 area1인 요소 얻어오기
    const area1 = document.getElementById("area1");
   
    // 2) area1 내부 내용을 모두 읽어오기
   // const content = area1.innerHTML;

    // 3) area1에 이전 내용 + 새로운 요소(div.box2) 추가
    //area1.innerHTML = content + "<div class='box2'></div>";

    //2번 + 3번
    area1.innerHTML += "<div class='box2'></div>";
}

function fnConfrim(){
    if(confirm("버튼 배경색을 초록색으로 바꾸시겠습니까?")){
        document.getElementById("confirmBtn").style.backgroundColor = "green";

    }else{
        document.getElementById("confirmBtn").style.backgroundColor = "yellow";

    }

}

//prompt 확인하기
function fnPrompt1(){
    var name = prompt("이름은 무엇입니까?");
    var age = prompt("나이는 몇살입니까?");
    //console.log(name);
    //console.log(age);

    const divE1 = document.getElementById("area2");
    divE1.innerHTML = "<b> "+name+age+ "살입니다.</b>";

}

function fnPrompt2(){
    const input = prompt("이름을 입력해주세요.");



 
    const divE2 = document.getElementById("area3");

    if(input !=null){    
        // 이름이 입력 되었을때
        //~님 환영합니다.

          divE2.innerText = input+"님 환영합니다.";

    }else{   //취소 버튼 눌렀을때
        // 이름을 입력해주세요.
          divE2.innerText="이름을 입력해주세요";

    }
}

function fnInput(){
    const input1 = document.getElementById("userId") ;//아이디 input 요소
    const input2 = document.getElementById("userPw");//비밀번호 input 요소

   // console.dir(input1);

   const id = input1.value;
   const pwd = input2.value;

   const area4 =document.getElementById("area4");
   //console.log(id);
   //console.log(pwd);
   area4.value = id+","+pwd;

   input1.value="";
   input2.value="";
}

 

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>02_데이터 입출력</title>
    <script src="js/02_데이터 입출력.js"></script>
    <style>
        .box{
            border: 1px solid black;
        }

        #area1{
            width:520px;
            height:300px;
            border:1px solid black;
            background-color: pink;
            display: flex;
            flex-wrap: wrap;
            align-content: flex-start;
            overflow: auto;

        }

        .box2{
            width:100px;
            height:100px;
            background-color: cornflowerblue;
            border:2px solid green;
        }
    </style>
</head>
<body>
   
    <h1>자바스크립트에서 데이터 입/출력</h1>

    <!--
        *window : 자바 스크립트 내장 객체로 브라우저 창이 열릴 때마다 하나씩 만들어지는 객체
                  브라우저 창 안에 존재하는 모든 요소들의 최상위 객체(생략 가능 )

        *document : 웹 문서마다 하나씩 만들어지는 객체
                    (html문서에 대한 정보들을 가지고 있음)
       
       
     -->

     <h2> 데이터를 출력하는 구문</h2>

     <pre>
        1) [window.]alert("알림창에 출력할 문구");
        2) [window.]console.log("콘솔창에 출력할 문구");
        3) document.write("화면에 출력할 문구");
        4) 선택한요소.innerText = "요소에 출력할 문구";
        5) 선택한요소.innerHTML = "요소에 출력할 문구";
     </pre>

     <hr>

     <h3>1) window.alert("내용")</h3>
     <pre>
        - alert : 알리다, 경보, 경고
        - 브라우저에 대화상자를 띄우는 함수
     </pre>

     <!-- 클릭시 "alert 버튼 클릭됨 대화상자 출력" -->
     <button onclick="btnAlert()">alert 확인</button>

     <hr>

     <h3> 3) document.write("내용")</h3>
     <button onclick="documentWrite()">화면에 출력</button>

     <hr>

     <h3> 4) innerText</h3>

     <pre>
        자바스크립트에서 요소에 작성된 내용을 읽어들이거나 변경하는 속성

        - 내용을 읽어올 때 태그는 모두 무시함
        - 내용을 변경할 때 태크는 문자열 자체로 해석됨. (태그 해석 x)
     </pre>

     <p id="test1" class="box">
        테스트 1입니다.
        <br>
        <b>점심 뭐 먹지?</b>
    </p>

     <button onclick="getInnerText()">innerText로 읽어오기</button>
     <button onclick="setInnerText()">innerText로 변경하기</button>

     <hr>

     <h3> 5) innerHTML</h3>
     <pre>
        자바스크립트에서 요소 전체를(태그 + 속성 + 내용) 읽어드리거나 변경하는 속성

        - 내용을 읽어올 때 태그 + 속성도 모두 포함함

        - 내용을 변경할 때 태그는 HTML 요소로 해석 됨 (태그 해석 O)


     </pre>

     <p id="test2" class="box">
        테스트 2입니다.
        <br>
        <b>점심 뭐 먹지?</b>
    </p>

     <button onclick="getInnerHTML1()">innerHTML로 읽어오기</button>
     <button onclick="setInnerHTML1()">innerHTML로 변경하기</button>

     <h3>innerHTML 응용</h3>

     <button onclick="add()">추가하기</button>

     <div id="area1">
        <div class="box2"></div>
     </div>

    <hr>
    <h2>2. 데이터를 입력받는 구문(변수에 기록 가능)</h2>

    <pre>
        1) 변수 = [window.]confirm("질문 내용");
        2) 변수 = [window.]prompt("질문 내용");
        3) 변수 = 선택한요소.속성(id,className, innerHTML, innerText....);
        4) 변수 = 선택한 input요소.value;
    </pre>

    <h3>1) window.confirm("내용")</h3>
    <pre>
        질문에 대한 "예"/ "아니오" 결과를 얻고자 할 때 사용하는
        대화 상자 출력 함수
        -> 선택 결과에 따라서 확인 버튼 클릭시 true 또는
                              취소버튼 쿨릭시 flase 반환
                           
    </pre>

    <button id="confirmBtn" onclick="fnConfrim()">confirm 확인하기</button>

    <hr>

    <h3>2) window.prompt("내용")</h3>
    <pre>
        - 텍스트를 작성할 수 있는 대화상자

        - 확인 : 입력한 값 반환(문자열)
        - 취소 : null 반환

    </pre>

    <button onclick="fnPrompt1()">클릭</button>
    <div id="area2"></div>

    <br>
    <button onclick="fnPrompt2()">확인</button>
    <div id="area3"></div>

    <hr>

    <h3>4) 선택한 input 요소.value</h3>

    아이디 : <input type="text" id="userId"><br>
    비밀번호 : <input type="password" id="userPw"><br>

    <button onclick="fnInput();">클릭</button>
    <br>
    <input type="text" id="area4">

</body>
</html>

 

728x90
반응형

'괴발개발 > js' 카테고리의 다른 글

문자열 숫자형 변환  (0) 2024.06.18
정규표현식  (0) 2024.06.17
자바스크립트 js 이벤트  (0) 2024.06.14
요소 접근 방법  (0) 2024.06.13
javascript 개요  (1) 2024.06.12