
1. 토글로 하기
- id를 안주면 id를 못찾는데 어떻게 바꿀 수 있을까?
e.타겟을 찾아서 하면 됨
- 이벤트를 찾아서 타겟을 받으면 DOM을 찾을 수 있음
<!DOCTYPE html> <html> <head> <title>Font Awesome 5 Icons</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> <style> .my-cursor { cursor: pointer; } .my-love { color: red; } </style> </head> <body> <i onclick="loveToggle(event)" class="fas fa-heart my-cursor"></i> <script> let check = -1; function loveToggle(e) { console.log(e.target); if (check == -1) { $(e.target).addClass("my-love"); } else { $(e.target).removeClass("my-love"); } check = check * -1; } </script> </body> </html>


2. boolean으로 하기
- isLike : 전역변수
- isLike를 역치만 해주면 됨
<!DOCTYPE html> <html> <head> <title>Font Awesome 5 Icons</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> <style> .my-cursor { cursor: pointer; } .my-love { color: red; } </style> </head> <body> <i onclick="loveToggle(event)" class="fas fa-heart my-cursor"></i> <script> let isLike = false; function loveToggle(e) { console.log(e.target); if (isLike == true) { $(e.target).addClass("my-love"); } else { $(e.target).removeClass("my-love"); } isLike = !isLike; } </script> </body> </html>


3. 클래스를 넣다 뺏다 하기 / 이게 제일 좋음
<!DOCTYPE html> <html> <head> <title>Font Awesome 5 Icons</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> <style> .my-cursor { cursor: pointer; } .my-love { color: red; } </style> </head> <body> <i onclick="loveToggle(event)" class="fas fa-heart my-cursor"></i> <script> function loveToggle(e) { console.log(e); $(e.target).toggleClass("my-love"); } </script> </body> </html>


- 클라이언트 사이드 랜더링 할 때 사용
무조건 사용하는 것은 아님
ex) 검색을 하다 좋아요를 누르면 검색 글자가 남아있음
ex) 휴대폰 인증하기
- 클릭해서 서버쪽으로 인서트하고 색깔이 있는 전체 페이지를 다운 받아도 됨
ex) 검색하다 좋아요를 누르면 검색 글자가 없어짐
4. onclick이 아닌 id 만들어서 해보기
- 이벤트를 받을 필요가 없음
<!DOCTYPE html> <html> 되게 티 <head> <title>Font Awesome 5 Icons</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> <style> .my-cursor { cursor: pointer; } .my-love { color: red; } </style> </head> <body> <i id="love-1" class="fas fa-heart my-cursor"></i> <script> $("#love-1").click(() => { $("#love-1").toggleClass("my-love"); }); </script> </body> </html>


Share article