course/spartacoding

[웹개발 종합반] 2주차 (1) jQuery

hjkim0502 2021. 10. 28. 19:06
  • js 복습
    • <head>
          <script>
              let cnt = 1;
              function hey() {
                  if (cnt % 2 == 0) {
                      alert ('even')
                  } else {
                      alert ('odd')
                  }
                  cnt += 1
              }
          </script>
      </head>
      <body>
      	<a onclick="hey()" class="btn btn-primary btn-lg" href="#" role="button">포스팅박스 열기</a>
      </body>
      클릭 수에 따라 다른 alert 창 띄우기
    • cnt를 함수 밖에 설정해야 축적이 됨
  • jQuery는 길고 복잡한 js 코드를 간단하게 쓸 수 있도록 미리 만들어진 라이브러리 (따라서 import 필수!)
    • bootstrap에 이미 jQuery import 되어있음
    • bootstrap 사용하지 않을 때는 jQuery CDN을 html head에 복사
    • // id 값이 article-url인 곳을 가리키고, val()로 입력값을 가져온다 - input box의 경우
      $('#article-url').val();
      
      // id 값이 article-url인 곳을 가리키고, 입력값을 'something'으로 한다 - input box의 경우
      $('#article-url').val('something');
      
      // id 값이 btn-posting-box인 곳을 가리키고, 입력값을 'something'으로 한다 - 나머지 경우
      $('#btn-posting-box').text('something');
      
      // 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');
      
      $('#post-box').show();
      $('#post-box').css('display');
      
      // html 요소 추가하기
      let temp_html = '<button>나는 추가될 버튼이다!</button>';
      $('#cards-box').append(temp_html);
      
      // 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);
    • html에서 지칭할 대상에 id 부여하고, js에서 id 값으로 지칭 후 명령 수행
    • append 하면 해당 태그의 맨 밑 자식태그로 추가됨
    •     <script>
              function openclose() {
                  let status = $('#post-box').css('display')
                  if (status == 'block') {
                      $('#post-box').hide()
                      $('#btn-posting-box').text('포스팅박스 열기')
                  } else {
                      $('#post-box').show()
                      $('#btn-posting-box').text('포스팅박스 닫기')
                  }
              }
          </script>
      포스팅 박스 열고 닫는 기능 구현
    • 애초에 포스팅박스는 css에 display: none으로 안 보이게끔 설정
    • <!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() 이렇게!
                  // 2. 만약 입력값이 빈칸이면 if(입력값=='')
                  // 3. alert('입력하세요!') 띄우기
                  // 4. alert(입력값) 띄우기
                  let input = $('#input-q1').val()
                  if (input == '') {
                      alert('입력하세요!!')
                  }
              }
      
              function q2() {
                  // 1. input-q2 값을 가져온다.
                  // 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
                  // 3. info.spartacoding@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
                  // 4. alert(도메인 값);으로 띄우기
                  // 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
                  let input = $('#input-q2').val()
                  if (input.includes('@')) {
                      let domain = input.split('@')[1].split('.')[0]
                      alert(domain)
                  } else {
                      alert('이메일이 아닙니다')
                  }
              }
      
              function q3() {
                  // 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
                  // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
                  // 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
                  let input = $('#input-q3').val()
                  let temp_html = `<li>${input}</li>`
                  $('#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>
      jQuery 추가 연습