본문 바로가기
WEB

[WEB/JS] 출력/이벤트 처리

by IT 정복가 2022. 7. 6.
728x90

자바스크립트는 HTML 위에서 동작하기때문에

HTML 코드 중간에 코드를 작성해주면 된다.

 

아래처럼 HTML 코드가 있을 때 

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    
  </body>
</html>

자바스크립트를 중간에 삽입하고 싶으면 <script>태그를 만들어 주면 된다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script>
      document.write("Hello World!");
    </script>
  </body>
</html>

body태그 안에 script태그가 위치해 있는 것을 볼 수 있다.

script 태그 안에는 document.write()라는 문법이 나와 있는데 

이것은 출력을 의미한다.

자바로 치면 System.out.print() 느낌(?)

 

웹페이지에서도 출력된 것을 확인할 수 있다.

*자바스크립트는 HTML과 달리 계산도 출력해준다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>JavaScript</h1>
    <script>
      document.write(1+1);
    </script>
    <h1>HTML</h1>
    1+1
  </body>
</html>

자바스크립트와 HTML 모두에게 1+1이라는 코드를 입력했을때

HTML은 1+1을 그대로 출력하지만

자바스크립트 같은 경우는 1과 1을 더한 2가 출력이 된다.


자바스크립트는 이벤트도 처리할 수 있다.

우선 버튼을 만들어 보겠다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="button">
  </body>
</html>

input type="button"을 해주게 되면 웹페이지에 버튼이 생성된다.

이 버튼에 글자를 추가하고 싶다면 value 속성을 이용하면 된다.

<input type="button" value="검색">

또한 이 버튼을 클릭했을 때 알림창이 뜨는 이벤트를 처리할 수 있는데

이 때 쓰는 이벤트가 onclick="alert(' ')" 이벤트이다.

<input type="button" value="검색" onclick="alert('검색버튼이 눌렸습니다.')">

버튼을 만들고 버튼의 텍스트에 검색을 넣고 버튼을 눌렀을 때 알림창이 뜨는 코드이다.


 

input type="button" 말고 input type="text"를 하게 되면 검색창이 생기는 것을 

확인 할 수 있다.

<input type="button" value="검색" onclick="alert('검색버튼이 눌렸습니다.')">
<input type="text">

만약 검색창에 글자를 하나 입력할 때마다 알림창이 뜨게 하고 싶다면

onkeydown 이벤트를 사용할 수있다.

<input type="button" value="검색" onclick="alert('검색버튼이 눌렸습니다.')">
<input type="text" onkeydown="alert('키를 입력하였습니다!')">


참고한 생활코딩 자료

https://opentutorials.org/course/3085/18782

 

HTML과 JavaScript의 만남 2 (이벤트) - 생활코딩

소스코드 변경사항

opentutorials.org

728x90