jQuery click event : attr() / slice() / replace() / class 추가, 제거

Study/jQuery

2022.12.09.

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 61



Review


 

 어제부터 jQuery 수업을 시작했다. 

JavaScript보단 문법이 훨씬 간편하고 쉽지만, 그래도 쉽지 않다.

 

사실 블로그 포스팅이 조금씩 느려지고 있는 이유는 수업을 잘 이해하지 못해 혼자 정리하는

시간이 늘어나고 있기 때문이다. 일을 마치고 GTQ 시험도 준비하고, 유튜브로 강의도 듣고

있다. 결국 공부는 혼자 이해하고 복습해야하지만, 요즘은 수업을 들으며 이게 맞나 싶은 생각

이 들 때가 있다. 

 

선생님 수업 방식이 나와 잘 맞지 않다는 건 예전부터 생각하고 있었지만,

요즘 난도가 점점 올라가면서 선생님께서 오류를 잡지 못해 학생들이 도와주는 경우가 잦아

지고 있다. 결국 학생들에게 지금 이 시간은 정말 귀하기때문에 요즘은 속상하긴 하다.

선생님도 물론 나름의 고충이 있으시겠지만... 질문을 많이 해서 터득하는 수밖에 없을 것

같다.

 

지극히 개인적인 의견이지만 결론은 비전공자가 국비 교육을 듣는다면 독학을 각오하고

시작하는 것이 좋다 !  나도 각오하고 시작했지만 만만찮다. 

더 공부하고 더 노력하는 수밖에 없다.

 

파이팅 !

 

 


 

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 61

 

 

<어제 했던 click event 예제 다시 실행하기>

 

 

- HTML

 

    <div id="wrap">
      <div id="nav">
        <ul>
          <li><a href="#">Photo1</a></li>
          <li><a href="#">Photo2</a></li>
          <li><a href="#">Photo3</a></li>
          <li><a href="#">Photo4</a></li>
        </ul>
      </div>
      <div id="photo">
        <img src="img/photo1.jpg" alt="photo1" />
      </div>
    </div>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 130px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #222222;
      }

      #wrap {
        width: 500px;
        margin: 0 auto;
      }

      ul li {
        float: left;

        width: 25%;

        text-align: center;
      }

      ul li a {
        display: block;
      }

      ul li a:hover {
        background: #222222;
        color: #fff;
      }

      #photo img {
        width: 500px;
      }

 

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("ul li a").click(function (e) {
          e.preventDefault();
          let txt = $(this).text(); // this는 클릭한 나 자신
          let img_path = $("img").attr("src");

          /*   $("img")
              .attr(
                "src",
                 img_path.replace(img_path.slice(-5, -4), txt.slice(-1))
               )
              .attr("alt", txt);   */

          $("img").attr({
            src: img_path.replace(img_path.slice(-5, -4), txt.slice(-1)),
            alt: txt;
          });
        });
      });
      
    </script>

 

 

스크립트를 보면 맨 밑에 다른 방식으로 문법을 작성하는 방식을 배웠다.

 

 

 

0

결과는 어제 한 예제와 동일하다.

 

 

 


 

 

<CSS에서 class를 추가한 후 jQuery로 불러오기>

 

 

- HTML

 

    <div id="wrap">
      <div id="nav">
        <ul>
          <li><a href="#">Photo1</a></li>
          <li><a href="#">Photo2</a></li>
          <li><a href="#">Photo3</a></li>
          <li><a href="#">Photo4</a></li>
        </ul>
      </div>
      <div id="photo">
        <img src="img/photo1.jpg" alt="photo1" />
      </div>
    </div>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 130px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #222222;
      }

      #wrap {
        width: 500px;
        margin: 0 auto;
      }

      ul li {
        float: left;

        width: 25%;

        text-align: center;
      }

      ul li a {
        display: block;
      }

      ul li a:hover,
      ul li a.on {
        background: #222222;
        color: #fff;
      }

      #photo img {
        width: 500px;
      }

 

 

ul li a.on 이라고 작성해서 a 태그에가 on 이라는 클래스를 추가한 것이다.

그 클래스에 CSS 속성을 적용했다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("ul li a").click(function (e) {
          e.preventDefault();
          let num = $(this).parent().index(); // this는 클릭한 나 자신
          console.log(num);
          let img_path = $("img").attr("src");

          $("img").attr({
            src: img_path.replace(img_path.slice(-5, -4), num + 1),
            alt: $(this).text(),
          });

          $("ul li a").attr("class", "");
          $(this).attr("class", "on");
        });
      });
      
    </script>

 

attr로 class를 불러오고, 클릭할 때 클릭한 a 태그의 클래스 'on'이 추가된다.

 

0

클래스를 적용했기 때문에 a 태그를 누르면 CSS에서 적용했던 것처럼 background와 color가 남게 된다.

 

 

 


 

 

 

 

 

- HTML

 

    <div id="wrap">
      <div id="nav">
        <ul>
          <li><a href="#">봄</a></li>
          <li><a href="#">여름</a></li>
          <li><a href="#">가을</a></li>
          <li><a href="#">겨울</a></li>
        </ul>
      </div>
      <div id="photo" class="p01"></div>
    </div>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 130px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #222222;
      }

      #wrap {
        width: 500px;
        margin: 0 auto;
      }

      ul {
        overflow: hidden;
      }

      ul li {
        float: left;

        width: 25%;

        text-align: center;
      }

      ul li a {
        display: block;
      }

      ul li a:hover,
      ul li a.on {
        background: #222222;
        color: #fff;
      }

      #photo {
        width: 500px;
        height: 500px;
      }

      .p01 {
        background: url(img/photo1.jpg);
      }

      .p02 {
        background: url(img/photo2.jpg);
      }

      .p03 {
        background: url(img/photo3.jpg);
      }

      .p04 {
        background: url(img/photo4.jpg);
      }

 

 

HTML에서는 .p01 이라는 class만 만들었지만,

CSS에서는 .p02, .p03, .p04 라는 class를 더 만들고, 각각 background까지 적용했다.

기존에 있던 .p01에도 역시 background를 적용했다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("ul li a").click(function (e) {
          e.preventDefault();
          let i = $(this).parent().index();
          // parent()는 클릭할 때 부모 요소, index()는 순서
          let txt = $("#photo").attr("class");

          $("#photo").attr("class", txt.replace(txt.slice(-1), i + 1));
        });
      });
      
    </script>

 

 

 

i 라는 함수를 만들어 순서대로 이미지가 나타나도록 했다.

index는 0부터 시작하기 때문에 마지막에 i + 1이라고 작성한 것이다.

 

 

0


 

 

<addClass(), addAttr(), removeClass(), removeAttr() 알아보기>

 

 

- HTML

 

    <div id="wrap">
      <div id="nav">
        <ul>
          <li><a href="#">봄</a></li>
          <li><a href="#">여름</a></li>
          <li><a href="#">가을</a></li>
          <li><a href="#">겨울</a></li>
        </ul>
      </div>
      <div id="photo" class="p01"></div>
    </div>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 130px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #222222;
      }

      #wrap {
        width: 500px;
        margin: 0 auto;
      }

      ul {
        overflow: hidden;
      }

      ul li {
        float: left;

        width: 25%;

        text-align: center;
      }

      ul li a {
        display: block;
      }

      ul li a:hover,
      ul li a.on {
        background: #222222;
        color: #fff;
      }

      #photo {
        width: 500px;
        height: 500px;
      }

      .p01 {
        background: url(img/photo1.jpg);
      }

      .p02 {
        background: url(img/photo2.jpg);
      }

      .p03 {
        background: url(img/photo3.jpg);
      }

      .p04 {
        background: url(img/photo4.jpg);
      }

 

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("ul li a").click(function (e) {
          e.preventDefault();
          let i = $(this).parent().index() + 1;
          // parent()는 클릭할 때 부모 요소, index()는 순서
          let txt = $("#photo").attr("class");

          //   $("ul li a").removeClass();
          $("ul li a").removeAttr("class");

          $(this).addClass("on");
          $("#photo")
            .removeClass()
            .addClass("p0" + i);
        });
      });
      
    </script>

 

문법 순서대로 보면 removeAttr() 메소드를 이용해서 class를 먼저 없애고, 

클릭할 때마다 요소에서 보면 또 한번 더 없애고 나서  class .on이 추가되는 것을 볼 수 있다.

 

 

0

 

 

 

 


 

 

 

 

- HTML

 

    <div id="wrap">
      <div id="nav">
        <ul>
          <li><a href="#">봄</a></li>
          <li><a href="#">여름</a></li>
          <li><a href="#">가을</a></li>
          <li><a href="#">겨울</a></li>
        </ul>
      </div>
      <div id="photo" class="p01"></div>
    </div>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 130px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #222222;
      }

      #wrap {
        width: 500px;
        margin: 0 auto;
      }

      ul {
        overflow: hidden;
      }

      ul li {
        float: left;

        width: 25%;

        text-align: center;
      }

      ul li a {
        display: block;
      }

      ul li a:hover,
      ul li a.on {
        background: #222222;
        color: #fff;
      }

      #photo {
        width: 500px;
        height: 500px;

        background: url(img/photo1.jpg);
      }

 

위의 예제에서 만들었던 class 서식을 지우고, #photo에다가 background image를 넣었다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("#photo").css("background", "url(img/photo1.jpg)");

        $("ul li:first a").addClass("on");
        // $("ul li a").eq(0).addClass("on"); 위와 동일한 결과

        $("ul li a").click(function (e) {
          e.preventDefault();

          let i = $(this).parent().index() + 1;
          // parent()는 클릭할 때 부모 요소, index()는 순서
          let txt = $("#photo").attr("class");
          let bg_path = $("#photo").attr("style");

          //   $("ul li a").removeClass(); 아래와 동일한 결과
          $("ul li a").removeAttr("class");

          $(this).addClass("on");

          //   $("#photo").css("background", "url(img/photo" + i + ".jpg)");

          $("#photo").attr("style", bg_path.replace(bg_path.slice(-8, -7), i));
          // 맨 끝의 괄호부터 순서를 새야 함
        });
      });
      
    </script>

 

결과는 위와 동일한데, 이번에는 #photo에 넣은 background를 불러와 거기서 replace(), slice() 메소드를

이용하는 방식으로 작성했다. 아까 전보다 CSS가 간단해졌다.

 

 

 


 

 

 

<CSS에서 class를 만들고 jQuery에서 불러오기 응용 예제>

 

 

- HTML

 

    <button id="remove">remove</button>
    <button id="change">change</button>
    <button id="reset">reset</button>
    <p class="red underline">엘리먼트로부터</p>
    <p class="red underline">클래스를</p>
    <p class="red underline">추가하고</p>
    <p class="red underline">제거하는</p>
    <p class="red underline">연습</p>

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 100px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      a {
        text-decoration: underline;

        color: #222222;
      }

      .red {
        color: red;
      }

      .underline {
        text-decoration: underline;
      }

      .bg {
        background: yellow;
      }

      button {
        padding: 10px 20px;
        font-size: 18px;
      }

 

 

.red, .underline, .bg 라는 class를 만들었다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        // $("p").attr("class", "red underline");  밑과 결과 같음
        $("p").addClass("red underline");

        $("#remove").click(function () {
          //   $("p:even").removeClass();  밑과 같음
          $("p:even").removeAttr("class");
        });

        $("#change").click(function () {
          //   $("p:odd").removeClass();
          $("p:odd").removeAttr("class").attr("class", "bg");
        });

        $("#reset").click(function () {
          $("p").attr("class", "red underline");
        });
      });
      
    </script>

 

 

0

jQuery 너무 재밌는 것 같당...

 

 

 


 

 

<CSS에서 class를 만들고 jQuery에서 불러오기 응용 예제2>

 

: 이번에는 위의 예제에서 toggleClass()를 추가한 예제를 실행했다.

 

 

- HTML

 

    <button id="remove">remove</button>
    <button id="change">change</button>
    <button id="reset">reset</button>
    <button id="toggle">toggle</button>
    <p class="red underline">엘리먼트로부터</p>
    <p class="red underline">클래스를</p>
    <p class="red underline">추가하고</p>
    <p class="red underline">제거하는</p>
    <p class="red underline">연습</p>

 

toggle이라는 button을 하나 더 추가했다.

 

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        max-width: 1200px;

        margin: 100px auto;

        text-align: center;
        line-height: 50px;

        font-size: 18px;
      }

      a {
        text-decoration: underline;

        color: #222222;
      }

      .red {
        color: red;
      }

      .underline {
        text-decoration: underline;
      }

      .bg {
        background: yellow;
      }

      button {
        padding: 10px 20px;
        font-size: 18px;
      }

 

 

CSS는 위의 예제와 동일하다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        // $("p").attr("class", "red underline");  밑과 결과 같음
        $("p").addClass("red underline");

        $("#remove").click(function () {
          //   $("p:even").removeClass();  밑과 같음
          $("p:even").removeAttr("class");
        });

        $("#change").click(function () {
          //   $("p:odd").removeClass();
          $("p:odd").removeAttr("class").attr("class", "bg");
          $("p:even").removeClass("bg");
        });

        $("#reset").click(function () {
          $("p").attr("class", "red underline");
        });

        $("#toggle").click(function () {
          $("p:odd").removeClass("bg");
          $("p:even").toggleClass("bg");
        });
      });
      
    </script>

 

#toggle을 클릭했을 때의 함수를 하나 더 만들어주고 나서, 중요한 것이 있다.

#toggle을 클릭한 후에 #change를 클릭하면 class가 중복적용되어 p 모두에 bg가 적용된다.

 

그래서 각각의 함수에다가 서로의 class를 제거하는 문법을 작성해야한다.

 

#change를 클릭하고 나서 바로 #toggle을 클릭했을 때, 그리고 #toggle을 클릭하고 나서

바로 #change를 클릭할 때 2가지의 경우를 생각했다.

 

즉, 전자의 경우는 #toggle에서 #change에 적용되어 있는 class를 제거하는 문법인 $("p:odd").removeClass("bg");

를 작성해야 중복적용 되지 않는다.

후자의 경우는 #change에서 #toggle에 적용되어 있는 class를 제거하는 문법인  $("p:even").removeClass("bg");

를 작성해야 중복적용 되지 않는다.

 

 

0

이것 말고도 훨씬 많은 경우의 수가 있지만 전부 적용하려면 시간이 너무 많이 소요되어 여기까지만 했다.

중복적용이 되는 골치 아픈 문제가 있구나... 

 

 


 

 

<웹디자인기능사 실기 중 tab 메뉴 jQuery로 구현하기>

 

 

- HTML

 

    <div class="contents">
      <div class="col1">
        <ul class="tabBtn">
          <li>공지사항</li>
          <li>갤러리</li>
        </ul>
        <ul class="tabCon">
          <li>
            <table>
              <tr>
                <td><a href="#" id="open_popup">공지사항 첫 번째 아이템</a></td>
                <td>2022.12.09.</td>
              </tr>
              <tr>
                <td><a href="#">공지사항 두 번째 아이템</a></td>
                <td>2022.12.09.</td>
              </tr>
              <tr>
                <td><a href="#">공지사항 세 번째 아이템</a></td>
                <td>2022.12.09.</td>
              </tr>
              <tr>
                <td><a href="#">공지사항 네 번째 아이템</a></td>
                <td>2022.12.09.</td>
              </tr>
            </table>
          </li>
          <li>갤러리 내용입니다.</li>
        </ul>
      </div>
    </div>

    <div id="popup">
      <div class="pop">
        <h1>Popup Page</h1>
        <p>
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
          some text in the Modal<br />
        </p>
        <p><a href="#" id="close">Close</a></p>
      </div>
    </div>

 

 

 

 

- CSS

 

      @font-face {
        font-family: pretendard;
        src: url(../fontawesome-free-6.2.0-web/webfonts/Pretendard-Regular.woff)
          format("woff");
      }

      * {
        padding: 0;
        margin: 0;

        font-family: pretendard, sans-serif;
      }

      body {
        font-size: 18px;
      }

      ul,
      li {
        list-style: none;
      }

      a {
        text-decoration: none;

        color: #333;
      }

      .contents {
        width: 1280px;

        margin: 0 auto;
      }

      .col1 {
        position: relative;
        width: 33.333%;
      }

      .tabBtn li {
        position: absolute;
        width: 100px;
        height: 40px;

        z-index: 1;

        line-height: 40px;

        text-align: center;

        cursor: pointer;

        border: 1px solid #333;

        background: #ccc;
      }

      .tabBtn li:nth-child(2) {
        left: 100px;
      }

      .tabBtn li.on {
        background: #fff;
        border-bottom-color: #fff;
      }

      .tabCon {
        position: relative;
        top: 41px;

        height: 150px;
        border: 1px solid #333;
      }

      .tabCon li.on {
        display: none;
      }

      #popup {
        position: fixed;
        left: 0;
        top: 0;

        z-index: 2;

        width: 100%;
        height: 100%;

        background: rgba(0, 0, 0, 0.5);
      }

      .pop {
        position: absolute;
        left: 50%;
        top: 50%;

        width: 400px;

        background: #fff;

        padding: 30px;

        transform: translate(-50%, -50%);
      }

      .pop a {
        position: absolute;
        left: 400px;
      }

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        // $(".tabBtn li:fisrt").addClass("on");
        $(".tabBtn li").eq(0).addClass("on");
        $(".tabCon li:last").addClass("on");

        $("#popup").css("display", "none");

        $("#open_popup").click(function () {
          $("#popup").css("display", "block");
          return false;
        });

        $("#close").click(function (e) {
          e.preventDefault();
          $("#popup").css("display", "none");
        });

        $(".tabBtn li").click(function () {
          $(".tabBtn li").removeClass();
          $(this).addClass("on");

          let i = $(this).index();

		// 첫 번째 방법
          /*  if (i == 1) {
            $(".tabCon li").removeClass().eq(0).addClass("on");
          } else {
            $(".tabCon li").removeClass().eq(1).addClass("on");
          }  */

		// 두 번째 방법
          $(".tabCon li").removeClass().eq(i).siblings().addClass("on"); //siblings는 선택한 것 외에 나머지 형제 요소 선택
        });
      });
      
    </script>

 

 

0

 

와 CSS로만 만들었을 때는 진짜 복잡했었는데, jQuery로 하니까 뚝딱이다.

CSS에 class 하나만 만들어서 jQuery에서 추가했다가 뺐다가 하니 너무 간편하다. 

이제 웹디자인기능사 실기 문제 없겠군 !

 

HTML 만드는 것이 조금 헷갈려서 그것만 더 이해하고 적용해보면 될 것 같다.

 

 

 

 

 

 

 

 

 

 

 

 

* 내용 출처

: TCP School

 

* 이미지 출처

instagram: @postershop.kr

반응형