▶ function 문법
▸긴 코드를 짧은 단어로 축약
⌨️ <script> function 작명() {축약할코드} </scrpt>
<script>
function openAlert(){
document.getElementById('box').style.display = 'block';
}
</script>
▸ function문법 작명 규칙
1. 소문자 시작
2. camelCase
📌 주의 사항
- 조작할 HTML 하단에 코드를 짜야 잘된다.
- 셀렉터 오타 주의 (id찾을 때 주의)
- 그냥 기본 문법 오타
→ 크롬디버깅 이용
🔎 알림창 닫기 버튼 funtion문법으로 축약하기
[HTML]
<div id="box" class="alert-box">Alert!
<button onclick="closeAlert()">닫기</button>
</div>
<button onclick="openAlert()">버튼</button>
<script>
function openAlert(){
document.getElementById('box').style.display = 'block';
}
function closeAlert(){
document.getElementById('box').style.display = 'none';
}
</script>
▶ function의 파라미터
▸파라미터 예시 1.
⌨️ <script> function 작명(파라미터) {축약할코드} </scrpt>
<div id="box" class="alert-box">Alert!
<button onclick="alert('none')">닫기</button>
</div>
<button onclick="alert('block')">버튼</button>
<script>
function alert(any){
document.getElementById('box').style.display = any;
}
</script>
[HTML]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="box" class="alert-box">Alert!
<button onclick="alert('none')">닫기</button>
</div>
<button onclick="alert('block')">버튼</button>
<script>
/*function openAlert(){
document.getElementById('box').style.display = 'block';
}
function closeAlert(){
document.getElementById('box').style.display = 'none';
}*/
function alert(any){
document.getElementById('box').style.display = any;
}
</script>
</body>
</html>
▸파라미터 예시 2.
<script>
function plus(***num***){
***2+num***
}
plus(1);
plus(2);
</script>
▸파라미터는 여러개 가능하다.
📌 id로 찾기
⌨️ getElementById(’id’)
📌 class로 찾기
⌨️ getElementByClassName(’class name’)[0]
- [0]은 찾은 것 중에 몇번째 요소를 고를건지
📌 태그 안 텍스트 변경하기
⌨️ innerHTML
': ) Web > 웹 스터디' 카테고리의 다른 글
[JS] onclick 대신 이벤트리스너 사용하기 (0) | 2024.01.05 |
---|---|
[JS] [실습] function 문법 | alert 박스 만들기 (0) | 2024.01.05 |
[JS] Alert 박스 만들기 (1) | 2024.01.04 |
[HTML, CSS] [실습] CSS Grid로 레이아웃 만들기 (grid-column, grid-row이용) (0) | 2023.12.15 |
[HTML, CSS] CSS Grid 레이아웃 만들기 (0) | 2023.12.15 |