짝수/홀수 판단하는 방법
// 2로 나눈 나머지가 0이면 짝수
let even = 4;
console.log(even % 2);
// 2로 나는 나머지가 1이면 홀수
let odd = 5;
console.log(odd % 2);
짝수/홀수 onclick 함수
<script>
let count = 1;
function hey() {
if (count % 2 == 0) {
alert('짝짝짝👏');
} else {
alert('홀홀홀🎅');
}
count += 1;
}
</script>
HTML요소들을 조작하는, 편리한 Javascirpt를 미리 작성해둔 것. 라이브러리!
👉 Javascript로도 모든 기능(예 - 버튼 글씨 바꾸기 등)을 구현할 수 있지만,
1) 코드가 복잡 2) 브라우저 간 호환성 문제도 고려해야해서, JQuery라는 라이브러리가 등장함.
👉 jQuery는 Javascript와 다른 특별한 소프트웨어가 아니라 미리 작성된 Javascript 코드이다. 그렇기에, 사용하기 전에 "임포트" 필요!
ex. div태그 하나 감추고 싶을때
// 자바스크립트
document.getElementById("element").style.display = "none";
// JQuery
$('#element').hide();
미리 작성된 Javascript 코드를 가져오는 것 -> import
JQuery CDN
https://www.w3schools.com/jquery/jquery_get_started.asp
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
👉 css와 마찬가지로, jQuery를 쓸 때도 "가리켜야" → 조작할 수 있음.
예) 특정 인풋박스의 값을 → 가져와줘!
예) 특정 div를 → 안보이게 해줘!
👉 input 박스의 값 가져오기
<div class="form-group">
<label>아티클 URL</label>
<input type="url" class="form-control" id="article-url">
</div>
// 크롬 개발자도구 콘솔창에서 쳐보기
// id 값이 article-url인 곳을 가리키고, val()로 값을 가져온다.
$('#article-url').val();
👉 div 보이기 / 숨기기
<div class="posting-box" id="post-box">
<div class="form-group">
<label>아티클 URL</label>
<input type="url" class="form-control" id="article-url">
</div>
<div class="form-group">
<label for="comment">간단 코멘트</label>
<textarea class="form-control" id="comment" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">기사 저장</button>
</div>
// 크롬 개발자도구 콘솔창에 쳐보기
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.
// =css의 display 값을 none으로 바꾼다
$('#post-box').hide();
// show()로 보이게 한다.
// =css의 display 값을 block으로 바꾼다
$('#post-box').show();
👉 css의 값 가져오기
$('#post-box').hide();
$('#post-box').css('display'); // 500px
$('#post-box').show();
$('#post-box').css('display');
👉 태그 내 텍스트 입력하기
1) input box
$('#post-url').val('여기에 텍스트를 입력하면!');
2) 다른 것들 - 예) 버튼의 텍스트 바꾸기
// 가리키고 싶은 버튼에 id 값을 준다음
<button id="btn-posting-box" type="button" class="btn btn-primary">포스팅 박스 열기</button>
$('#btn-posting-box').text('포스팅 박스 닫기');
👉 태그 내 html 입력하기
<div>~</div>
내에 동적으로 html 넣고싶을때는? (ex. 포스팅되면 카드를 추가하고 싶다.)// 사이에 html을 넣고 싶은 태그에 id값을 준 다음
<div id="cards-box" class="card-columns">
<div class="card">
<img class="card-img-top" src="https://www.fodors.com/wp-content/uploads/2018/10/4_UltimateRome_PiazzaNavona-975x650.jpg" alt="Card image cap">
<div class="card-body">
<a href="https://naver.com/" class="card-title">여기 기사 제목이 들어가죠</a>
<p class="card-text">여기에 기사 내용이 들어가겠죠</p>
<p class="card-text comment">여기엔 코멘트가 들어갑니다</p>
</div>
</div>
</div>
1) 버튼을 넣어보기
let temp_html = '<button>나는 추가될 버튼이다!</button>';
$('#cards-box').append(temp_html);
2) 버튼 말고, 카드를 넣어보기
// 주의: 홑따옴표(')가 아닌 backtick(`)으로 감싸야 함.
// Mac에서 backtick(`): control + option+ ~
// backtick을 사용하면 문자 중간에 Javascript 변수 삽입 가능
let img_url = 'https://www.eurail.com/content/dam/images/eurail/Italy%20OCP%20Promo%20Block.adaptive.767.1535627244182.jpg';
let link_url = 'https://naver.com/';
let title = '여기 기사 제목이 들어가죠';
let desc = '기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...';
let comment = '여기에 코멘트가 들어갑니다.';
let temp_html = `<div class="card">
<img class="card-img-top"
src="${img_url}"
alt="Card image cap">
<div class="card-body">
<a href="${link_url}" class="card-title">${title}</a>
<p class="card-text">${desc}</p>
<p class="card-text comment">${comment}</p>
</div>
</div>`;
$('#cards-box').append(temp_html);
1. 완성된 모습 미리보기
'포스팅박스 열기' 버튼을 누르면 숨겨진 창이 나타나고 버튼의 내용이 '포스팅박스 닫기'로 바뀝니다. 다시 한 번 버튼을 클릭하면 원래 모습으로 돌아갑니다.
2. 포스팅 박스 열기 버튼에 function 붙이기
<script>
function openclose() {
// 여기에 jQuery를 이용해 코드를 짤 예정
}
</script>
// onclick 속성(attribute)을 추가합니다.
<button onclick="openclose()" class="btn btn-primary btn-lg">포스팅박스 열기</button>
3. 클릭 해서 포스팅 박스를 여닫게 하기
<div class="posting-box" id="post-box">
<div class="form-group">
<label>아티클 URL</label>
<input class="form-control" placeholder="">
</div>
<div class="form-group">
<label>간단 코멘트</label>
<textarea class="form-control" rows="2"></textarea>
</div>
<button type="button" class="btn btn-primary">기사 저장</button>
</div>
function openclose() {
// id 값 post-box 의 display 값이 block 이면
if($('#post-box').css('display') == 'block') {
// post-box를 가리고
$('#post-box').hide();
} else {
// 아니면 post-box를 보여라
$('#post-box').show();
}
}
<div class="posting-box" id="post-box" style="display:none">
<div class="form-group">
<label>아티클 URL</label>
<input class="form-control" placeholder="">
</div>
<div class="form-group">
<label>간단 코멘트</label>
<textarea class="form-control" rows="2"></textarea>
</div>
<button type="button" class="btn btn-primary">기사 저장</button>
</div>
요렇게 쓰는걸 inline-style (인라인 스타일) 이라고 부름.
여기저기 쓰면 복잡하겠지만, 이렇게 쓰면
직관적으로 "아 처음부터 안보이는 태그구나!"를 알 수 있다!(물론, class주고, css에서 display:none 속성 줘도 됨)
4. 포스팅박스 열기' 버튼의 글씨 바꿔주기
<button id="btn-posting-box" onclick="openclose()" class="btn btn-primary btn-lg">포스팅박스 열기</a>
function openclose() {
// id 값 post-box 의 display 값이 block 이면
if($('#post-box').css('display') == 'block') {
// post-box를 가리고
$('#post-box').hide();
// 버튼 숨겼으니까 열기로 버튼 바꿔두기
$('#btn-posting-box').text('포스팅 박스 열기');
} else {
// 아니면 post-box를 보여라
$('#post-box').show();
// 버튼 보이니까 닫기로 버튼 바꿔두기
$('#btn-posting-box').text('포스팅 박스 닫기');
}
}
function q1() {
// 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
let input_q1 = $('#input-q1').val();
// 2. 만약 입력값이 빈칸이면 if(입력값=='')
if(input_q1 == ''){
// 3. alert('입력하세요!') 띄우기
alert('입력하세요!');
} else {
// 4. alert(입력값) 띄우기
alert(input_q1);
}
}
function q2() {
// 1. input-q2 값을 가져온다.
let input_q2 = $('#input-q2').val();
// 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
if(input_q2.includes('@')){
// 3. info.spartacoding@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
let domain = input_q2.split('@')[1].split('.')[0];
alert(domain);
} else {
// 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
alert('이메일이 아닙니다.');
}
}
function q3() {
// 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
let input_q3 = $('#input-q3').val();
// 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
let temp_html = `<li>${input_q3}</li>`;
// 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
$('#names-q3').append(temp_html);
}
function q3_remove() {
// 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
$('#names-q3').empty();
}
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>jQuery 연습하고 가기!</title>
<!-- JQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
</style>
<script>
function q1() {
// 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
let input_q1 = $('#input-q1').val();
// 2. 만약 입력값이 빈칸이면 if(입력값=='')
if(input_q1 == ''){
// 3. alert('입력하세요!') 띄우기
alert('입력하세요!');
} else {
// 4. alert(입력값) 띄우기
alert(input_q1);
}
}
function q2() {
// 1. input-q2 값을 가져온다.
let input_q2 = $('#input-q2').val();
// 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
if(input_q2.includes('@')){
// 3. info.spartacoding@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
let domain = input_q2.split('@')[1].split('.')[0];
alert(domain);
} else {
// 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
alert('이메일이 아닙니다.');
}
}
function q3() {
// 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
let input_q3 = $('#input-q3').val();
// 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
let temp_html = `<li>${input_q3}</li>`;
// 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
$('#names-q3').append(temp_html);
}
function q3_remove() {
// 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
$('#names-q3').empty();
}
</script>
</head>
<body>
<h1>jQuery + Javascript의 조합을 연습하자!</h1>
<div class="question-box">
<h2>1. 빈칸 체크 함수 만들기</h2>
<h5>1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기</h5>
<h5>[완성본]1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기</h5>
<input id="input-q1" type="text" /> <button onclick="q1()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>2. 이메일 판별 함수 만들기</h2>
<h5>2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기</h5>
<h5>2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기</h5>
<h5>[완성본]2-3. 이메일 도메인만 얼럿 띄우기</h5>
<input id="input-q2" type="text" /> <button onclick="q2()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>3. HTML 붙이기/지우기 연습</h2>
<h5>3-1. 이름을 입력하면 아래 나오게 하기</h5>
<h5>[완성본]3-2. 다지우기 버튼을 만들기</h5>
<input id="input-q3" type="text" placeholder="여기에 이름을 입력" />
<button onclick="q3()">이름 붙이기</button>
<button onclick="q3_remove()">다지우기</button>
<ul id="names-q3">
<li>세종대왕</li>
<li>임꺽정</li>
</ul>
</div>
</body>
</html>