2주차 코딩 개발 일지(2-2 ~ 2-6)

영현·2022년 3월 6일
0

☑️ 자바스크립트 복습

  • 클릭 함수 만들기
    ✔︎ let count = 1; 를 함수 안에 넣으면 그 박스는 함수가 끝나면서 같이 끝난다.
 <script>
    function hey() {
        let count = 1;
        if (count % 2 == 0){
            alert('짝수입니다')
        } else {
            alert('홀수입니다')
        }
        count += 1;
        // count 사라짐, 축적이 안 됨
    }

</script>
  • 변수(let count = 1;)를 함수 밖에 넣었을 때
    ✔︎ 변수(let count)는 hey를 부르기 전 부터 1, 그 다음에 hey가 불려지면 count를 2로 나눴을 때 홀수가 나온다. 한번 더 누르면 짝수.
    ✔︎ 함수 밖에 써놓으면 함수 상관없이 어디서든 스크립트 안에서 쓸 수 있다.
<script>
    let count = 1;
    function hey() {
        if (count % 2 == 0){
            alert('짝수입니다')
        } else {
            alert('홀수입니다')
        }
        count += 1;
        // hey를 부르기 전 부터 1
    }

</script>

☑️ JQuery
HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 것. 라이브러리!

✔︎ Javascript로도 모든 기능(예 - 버튼 글씨 바꾸기 등)을 구현 가능

하지만,

1) 코드가 복잡
2) 브라우저 간 호환성 문제도 고려해야함
→ jQuery라는 라이브러리가 등장

  • 자바스크립트로 div 감출 때
document.getElementById("element").style.display = "none";
  • JQuery로 쓸 때
$('#element').hide();

⭐️ JQuery는 는 미리 작성된 자바스크립트 코드이다. 미리 누군가가 짜둔 코드를 가져 와서 사용 하는 것 (부트스트랩이랑 같은 맥락!)
⭐️ 따라서 임포트를 안 하면 쓸 수가 없다.

  • 부트스트랩 템플릿을 사용하지 않을 경우 아래 코드를 넣어서 임포트 해줘야한다.
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>


☑️ JQuery 다뤄보기

$('#id값') → 지칭 .val(); → 명령

// id 값이 post-url인 곳을 가리키고, val()로 값을 가져온다.
$('#post-url').val();
  • 박스 숨기고 나타나게 하는 코드
$('#post-box').hide()
$('#post-box').show()
  • css의 display 속성값 가지고 오기
$('#post-box').hide();
$('#post-box').css('display');

$('#post-box').show();
$('#post-box').css('display');
  • 텍스트 바꿔보기
$('#btn-posting-box').text('텍스트입력');
  • 태그 내 html 입력하기
   <div> ~ </div> 내에, 동적으로 html을 넣고 싶을 때는?
   html을 넣고 싶은 태그에 id값을 준 다음
   let temp_html = ''; 
   📌 주의: 홑따옴표(')가 아닌 backtick(`)으로 감싸야 함!
          ⭐️ 물결 키 버튼
       
   $('#cards-box').append(temp_html);
  • backtick을 사용하면 문자 중간에 Javascript 변수를 삽입할 수 있다.
let temp_html = ` <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>`
                
$('#cards-box').append(temp_html)


☑️ 열기/닫기 기능을 함께 붙여보기

  • 포스팅박스가 'block'이면 숨기고 버튼 텍스트는 ('포스팅박스 열기')로 나타낸다. 아니면 보여준 상태일때 버튼 텍스트는 ('포스팅박스 닫기')로 나타내라.
 <script>
        function openclose() {
            let status = $('#post-box').css('display');
            if (status == 'block') {
                $('#post-box').hide();
                $('#posting-box-btn').text('포스팅박스 열기');
            } else {
                $('#post-box').show();
                $('#posting-box-btn').text('포스팅박스 닫기');
            }
        }
    </script>
  • 포스팅박스 열기/닫기 완성
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>

    <title>스파르타코딩클럽 | 부트스트랩 퀴즈</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400&display=swap" rel="stylesheet">
</head>

    <style>
        .wrap {
            width: 900px;
            margin: auto;
        }

        * {
            font-family: 'IBM Plex Sans KR', sans-serif;
        }

        .comt {
            color: blue;
            font-weight: bold;
        }

        .postbox {
            display: none;
            // 페이지 처음 뜰때 안 보이게 설정

            width: 500px;
            margin: 0px auto 30px auto;

            border: 2px solid black;
            border-radius: 10px;

            padding: 50px

        }
    </style>
    <script>
        function openclose() {
            let status = $('#post-box').css('display');
            if (status == 'block') {
                $('#post-box').hide();
                $('#posting-box-btn').text('포스팅박스 열기');
            } else {
                $('#post-box').show();
                $('#posting-box-btn').text('포스팅박스 닫기');
            }

        }
    </script>

<body>
    <div class="wrap">
        <div class="jumbotron">
            <h1 class="display-4">나홀로 링크 메모장!</h1>
            <p class="lead">중요한 링크를 저장해두고, 나중에 볼 수 있는 공간입니다.</p>
            <hr class="my-4">
            <!--            <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>-->
            <p class="lead">
                <a id="posting-box-btn" onclick= "openclose()" class="btn btn-primary btn-lg" href="#" role="button">포스팅박스
                    열기</a>
            </p>
        </div>
        <div class="postbox" id="post-box">
            <div class="form-group">
                <label>아티클 URL</label>
                <input class="form-control" id="article-url">
            </div>
            <div class="form-group">
                <label for="exampleFormControlTextarea1">간단 코멘트</label>
                <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">기사저장</button>
        </div>
        <div class="card-columns" id="cards-box">
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
            <div class="card">
                <img class="card-img-top"
                     src="https://images.unsplash.com/photo-1495785870240-c8456d5aeda2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1473&q=80"
                     alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">
                        <a href="https://www.naver.com/">여기 기사 제목이 들어가죠</a>
                    </h5>
                    <p class="card-text">기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...</p>
                    <p class="card-text comt">여기에 코멘트가 들어갑니다.</p>
                </div>
            </div>
        </div>
    </div>

</body>

</html>

☑️Quiz

📌 퀴즈 보기

✦ 1번 : 빈칸 체크함수 만들기

-버튼을 눌렀을때 값이 입력되는지 확인해보기

function q1() {
             let txt = $('#input-q1').val();
             console.log(txt)      
        }       
    function q1() {
            let txt = $('#input-q1').val();
            if (txt == ''){
                alert('입력하세요!')
            } else {
                alert(txt)
            }
        }
        // 1. input-q1의 입력값을 가져온다. $('# ....').val() 
        // 2. 만약 입력값이 빈칸이면 if(입력값=='')
        // 3. alert('입력하세요!') 띄우기
        // 4. alert(입력값) 띄우기

✦ 2번 : 이메일 판별 함수 만들기

-문자열에 '@'가 포함되면 true, 없으면 false가 되는지 확인

function q2() {
            let txt = $('#input-q2').val();
            console.log(txt.includes('@'))
      }

-알림창 띄워주는 함수 확인

 function q2() {
             let txt = $('#input-q2').val();
             console.log(txt.includes('@'))

             if (txt.includes('@')) {
                 alert('이메일입니다')
             } else {
                 alert('이메일이 아닙니다')
             }
        }

-콘솔창에서 도메인만 추출하는 방법

let txt = 'sparta@naver.com'
  //sparta@naver.com 문자열을 부른다.

txt.split('@')
  //txt값에서 '@'만 뺀다.
(2) ['sparta', 'naver.com']
  //@를 제외한 [0번,1번] 값이 도출됨

txt.split('@')[1]
  //txt값에서 '@'만 빼고 나온 1번 값
'naver.com'
  // 1번 값이 도출됨
  
txt.split('@')[1].split('.')
  // txt값에서 '@'만 빼고난 1번 값에서 '.' 만 뺀다.
(2) ['naver', 'com']
  // '.'만 뺀 2개의 값이 도출
  
txt.split('@')[1].split('.')[0]
  // txt값에서 '@'만 빼고난 1번 값에서 '.' 빼고 나온 0번 값
'naver'
  // @과 .을 제외한 도메인 0번값 도출
 function q2() {
             let txt = $('#input-q2').val();
     
             if (txt.includes('@')) {
                 let domain = txt.split('@')[1].split('.')[0]
                 alert(domain)
             } else {
                 alert('이메일이 아닙니다')
             }
         }
            // 1. input-q2 값을 가져온다.
            // 2. 만약 가져온 값에 @가 있으면 (includes 이용)
            // 3. ex) spartacoding@gmail.com 에서 
                  → gmail만 추출 (.split('@') 을 이용)
            // 4. alert(도메인 값);으로 띄우기
            // 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
        

⭐️ 하나하나 해보면서 답을 찾아가야한다.

✦ 3번 : html붙이기/지우기

-붙일 태그가 잘 되는지 확인

function q3() {
             let txt = $('#input-q3').val();
             let temp_html = `<li>${txt}</li>`
             console.log(temp_html)
        }

-붙이기

function q3() {
             let txt = $('#input-q3').val();
             let temp_html = `<li>${txt}</li>`
            
             $('#names-q3').append(temp_html)
        }
            // 1. input-q3 값을 가져온다.
            // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다.
            // 3. 만들어둔 temp_html을 names-q3에 붙인다.
                  (jQuery의 $('...').append(temp_html)을 이용)

-모두 지우기

function q3_remove() {
            $('#names-q3').empty()
        }
            // 1. names-q3의 내부 태그를 모두 비운다.
                  (jQuery의 $('....').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의 입력값을 가져온다.
            let txt = $('#input-q1').val();
            // 2. 만약 입력값이 빈칸이면 if(입력값=='')
            if (txt == '') {
            // 3. ('입력하세요!') 띄우기
                alert('입력하세요!');
            } else {
            // 4. (입력값) 띄우기
                alert(txt);
            }
        }

        function q2() {
            // 1. input-q2 값을 가져온다.
            let txt = $('#input-q2').val();
            // 2. 만약 가져온 값에 @가 있으면 
            if (txt.includes('@')) {
            // 3. spartacoding@gmail.com 에서 gmail 만 추출해서
               let domain = txt.split('@')[1].split('.')[0]            
            // 4. alert(도메인 값);으로 띄우기
            	alert(domain);
            } else {
            // 5. 이메일이 아니면 '이메일이 아닙니다.' 띄우기
                alert('이메일이 아닙니다.');
            }
        }

        function q3() {
            // 1. input-q3 값을 가져온다.
            let txt = $('#input-q3').val();
            // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. 
            let temp_html = `<li>${txt}</li>`;
            }
            // 3. 만들어둔 temp_html을 names-q3에 붙인다.
            $('#names-q3').append(temp_html)
        }

        function q3_remove() {
            // 1. names-q3의 내부 태그를 모두 비운다.
            $('#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>

0개의 댓글