태그에 직접 간단한 코드를 작성하여 실행하는 방법
<button onclick="alert('버튼이 클릭되었습니다.');">경고창(알림창) 출력</button>
<button onclick="console.log('개발자도구 console에 출력');">console에 출력</button>
경고창(알림창) 출력
console에 출력
HTML 문서 내부(internal)에 script 태그를 선언하여 작성한다.
script 태그는 head, body 태그에 작성 가능하다.
<!-- 함수 호출 -->
<button onclick="testFn();">함수 호출 버튼</button>
<button onclick="add(10,20);">더하기</button>
<script>
// 함수( function == 기능(java의 method와 비슷함) )
// 함수는 선언, 정의, 호출 세 가지로 구분된다. (메서드와 같음)
// function 함수명( 매개변수 ){ } -> 함수 선언 기본 형식
// 함수 선언
function testFn() {
// 함수 정의
for (let i = 0; i < 10; i++) {
console.log(i);
}
};
// 매개변수가 있는 함수
function add(num1, num2) {
alert("두 수의 합 : " + (num1 + num2));
}
</script>
함수 호출 버튼
더하기
외부에 별도로 JS만 작성하는 .js 파일을 생성하여 연결하는 방법
<button onclick="sample1();">sample1 함수 호출</button>
<button onclick="sample2();">sample2 함수 호출</button>
<script src="js/02_JS작성방식.js"></script>