코딩하는 문과생

자바스크립트/ 01. 출력문과 입력문 본문

웹 프로그래밍/Javascript

자바스크립트/ 01. 출력문과 입력문

코딩하는 문과생 2018. 11. 3. 14:25

01. 출력문과 입력문


<출력문>


- innerHTML 사용하기


   HTML 요소에 접근하기 위해서 사용합니다. 


1
2
3
4
5
6
7
8
9
<body>
  <h2>My First Web Page</h2>
  <p>My First Paragraph</p>
  <p id="demo"></p>
 
  <script>
    document.getElementById("demo").innerHTML = "Hello JavaScript";
  </script>
</body>
cs


<실행결과>


- alert()


   특정 정보를 메시지 창으로 사용


1
2
3
4
5
<script>
  var x = "alert() 함수를 이용한 메시지 출력...";
  alert(x);
</script>
 
cs



<실행결과>




- document.write()


   HTML 문서 출력과 동일


예제1)

1
2
3
4
5
6
<script>
  var name = "hongGilDong";
  var age = 35;
  document.write("name = ", name, " age = ", age, "<br>");
  document.write("name = ", name, " age = ", age, "<br>");
</script>
cs


<실행결과>


예제2)

1
2
3
4
5
6
<body>
  <h2>My First Web Page</h2>
  <p>My first paragraph</p>
  <button type="button" onclick="document.write('Second Example...')">Try it</button>
</body>
 
cs


<실행결과>




- console.log()


   전문적인 출력문이라기보다는 오류를 잡아 없애는 디버깅을 위한 도구



- confrim()


   확인 버튼과 취소 버튼이 자동 출력







<입력문>

-prompt()


1
2
3
4
5
<script>
  var age = prompt("나이를 입력하시오: ")
  document.write(age);
</script>
 
cs

 

<실행결과>






-HTML 문서의 지정된 양식에 입력/출력하기


예제1)

1
2
3
4
5
6
7
8
9
10
<script>
  function inputFun(){
    var x = document.getElementById("input_id").value;
    document.getElementById("output_id").value = x;
  }
</script>
입력:<input type="text" id="input_id" size=10>
출력:<input type="text" id="output_id" size=10>
<button onclick="inputFun()">클릭</button>
 
cs

<실행결과>


예제2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
  function Calc(){
    var x = Number(document.calculator.number1.value);
    var y = Number(document.calculator.number2.value);
    var result_Add = x + y;
    document.calculator.result.value = result_Add;
  }
</script>
<form name="calculator">
  입력1:<input type="text" name="number1" size=10>
  입력2:<input type="text" name="number2" size=10>
  결과:<input type="text" name="result" >
</form>
<button onclick="Calc()">ADD</button>
 
cs


<실행결과>