기록

*67일차 (jQuery) 본문

학원/강의

*67일차 (jQuery)

pringspring 2022. 5. 2. 21:28

@jQuery

  • 자바스크립트 라이브러리
  • slim 쓰지말기

 

<div>
    <p id="p1" class="group1">안녕1</p>
    <p id="p2" class="group1">안녕2</p>
    <p id="p3" class="group2">안녕3</p>
    <p id="p4" class="group2">안녕4</p>
    <p id="p5" class="group1 group2">안녕5</p>
  </div>
  <button id="btn1">선택자</button>
  <button id="btn2">js객체</button>
  <script>
  btn1.addEventListener('click', () => {
    // $(선택자) : jquery객체를 반환
    // const $group1 = $(".group1");
    // console.log($group1);
    // // console.log($group1.css('background-color', 'springgreen')); 
    
    // // jquery객체 다시 반환. method chain
    // $group1
    //   .css('background-color', 'springgreen')
    //   .css('font-weight', 'bold');
    
    // jquery버젼 : 각요소에 대한 반복처리, 메소드체이닝 가능
    $(".group1")
      .css('background-color', 'springgreen')
      .css('font-weight', 'bold');

    // vanilla js버젼 : 각요소에 대한 반복처리를 직접 진행
    const group1 = document.querySelectorAll(".group1");
    group1.forEach((el, index) => {
      el.style.backgroundColor = 'springgreen';
      el.style.fontWeight = 'bold';
    });

    $("#p1").css("font-size", "2em");
  });  


  /**
   * $(js객체):jquery객체 반환
   */
  btn2.addEventListener('click', () => {
    // console.log($("#p1"));
    // console.log($(p1));
    // $(p1).css("color", "hotpink");

    // const $ppp = $("#p1,#p2,#p3"); // , 사용시 공백제거할 것!
    const $ppp = $([p1, p2, p3]);
    console.log($ppp);
    $ppp.css("color", "tomato");
  });
  </script>

 

*이벤트명과 동일한 이벤트핸들링 메소드 제공

  • css에 없는 가상선택자
  • text
  • password
  • radio
  • checkbox
  • button
  • submit
$(btn3).click(() => {
    $(":text")
      .css("background-color", "tomato")
      .css("color", "white");
    
    $(":password")
      .css({
        "background-color": "yellowgreen",
        "color" : "white"
      });
    
    $(":radio,:checkbox").prop("checked", true); // 체크처리
    $(":button").val("클릭했음!");      

  });
  </script>
<table id="people">
    <!-- thead>tr>th*3 -->
    <thead>
      <tr>
        <th>이름</th>
        <th>혈액형</th>
        <th>주소</th>
      </tr>
    </thead>
    <tbody>
      <!-- tr>td*3 -->
      <tr>
        <td>홍길동</td>
        <td>A</td>
        <td>서울시 강남구</td>
      </tr>
      <tr>
        <td>신사임당</td>
        <td>AB</td>
        <td>서울시 강서구</td>
      </tr>
      <tr>
        <td>장영실</td>
        <td>B</td>
        <td>서울시 강북구</td>
      </tr>
      <tr>
        <td><a href="#">이순신</a></td>
        <td>O</td>
        <td>서울시 강동구</td>
      </tr>
    </tbody>
  </table>

-----------테이블

 

 

*순서관련

  • odd
  • even
  • first - css에서는 :first-child, :first-of-type
  • last - css에서는 :last-child, :last-of-type
  •  
  • eq(n)
  • gt(n)
  • lt(n)
  •  
  • contains(text) 컨텐츠 텍스트 포함여부 (자식, 후손)
  • has(selector) 해당선택자 자식요소 포함여부
 $(btn4).click(() => {
    // zero-based index
    // const $selected = $("#people tr:odd");
    // const $selected = $("#people tr:even");
    // const $selected = $("#people tr:first");
    // const $selected = $("#people tr:last");
    
    // const $selected = $("#people tr:eq(3)");
    // const $selected = $("#people tr:gt(0)");
    // const $selected = $("#people tr:lt(1)");

    // const $selected = $("#people tr:contains('A')");
    const $selected = $("#people td:has(a)");
    
    $selected.css({
      "background-color" : "gray",
      "color" : "white"
    });
  });
  </script>

 

@attr_prop

 

*attr메소드

  • 문서객체에 작성된 속성관리
  • 해당속성을 가져오거나(getter - attr(속성명)) 설정하는(setter - attr(속성명, 속성값)) 메소드
  • getter : 첫번째 요소의 값 반환
  • setter : 모든 요소의 값 설정
 
$(btn1).click(() => {
    const $img = $("img");
    console.log($img);

    // getter
    console.log($img.attr('src'));

    // setter
    $img.attr('src', '../sample/image/flower3.PNG');
  });
  </script>

 

*prop

  • 속성값 관리에 t/f 논리형이 필요한 경우에 사용
  • 자바스크립트를 이용한 동적제어 checked
<fieldset>
    <legend>prop</legend>
    <input type="checkbox" id="checkAll">
    <label for="checkAll">전체선택/전체해제</label>
    <!-- (input:checkbox[name=menu][value]#menu$+label[for=menu$])*3 -->  
    <input type="checkbox" name="menu" id="menu1" value="피자">
    <label for="menu1">피자</label>
    <input type="checkbox" name="menu" id="menu2" value="햄버거" checked="checked">
    <label for="menu2">햄버거</label>
    <input type="checkbox" name="menu" id="menu3" value="핫도그">
    <label for="menu3">핫도그</label>
    <br><br>
    <button id="btn2">확인</button>
  </fieldset>
  <script>
  
  $(btn2).click(() => {
    const $menu = $("[name=menu]");
    // console.log($menu);
    // $menu.prop('checked', true);
    
    // console.log($menu.attr('checked')); // html태그에 checked속성값이 있는가? 있으면 가져오기

    // 체크한 값 확인
    // jquery객체안의 요소에 대한 반복처리 each
    const menuChecked = [];
    $menu.each((index, menu) => {
      // console.log(index, menu); // menu는 순수 js 태그객체
      // console.log(menu, $(menu));
      // console.log(menu.value, $(menu).val());
      console.log(menu.checked, $(menu).prop('checked'));

      if(menu.checked)
      // if($(menu).prop('checked'))
        menuChecked.push($(menu).val()); // value 속성 가져오기
    });

    alert(menuChecked);
  });

  $(checkAll).change((e) => {
    const checked = $(e.target).prop('checked'); // getter
    $("[name=menu]").prop("checked", checked);
  });
  </script>

 

 

@filter

  • filter (selector)
  • filter (callback)

 

*filter

 

$(btn1).click(() => {
    const $p = $("p");
    // console.log($p);

    // 선택자
    // $p
    //   .filter(".group1") // #p1, #p2, #p5
    //   .css("color", "hotpink")
    //   .filter(":gt(0)") // #p2, #p5
    //   .css("background-color", "blue");

    // callback함수
    $p
      .filter((index, p) => {
        console.log(index, p);
        return index % 2 == 0;  // false를 반환하면 제거
      })
      .css("background-color", "cyan");

  });

 

*first | last

 $(btn2).click(() => {
    const $p = $("p");

    $p.first().css("background-color", "springgreen");
    $p.last().css("background-color", "yellowgreen");

  });

 

* eq(index) | end

  $(btn3).click(() => {
    console.log(
      $("p")
        .eq(2) // #p3
        .css("background-color", "magenta")
        .end() // 이전 상태로 돌아감 (prevObject속성상태)
        .css("text-decoration", "underline")
    );
  });

 

* not(selector)

  $(btn4).click(() => {
    $("p")
      .not(".group1.group2") // #p1, #p2, #p3, #p4
      .css("text-decoration", "underline");
  });

'학원 > 강의' 카테고리의 다른 글

*72일차 (server 시작)  (0) 2022.05.10
*71일차 (git)  (0) 2022.05.09
*65일차 (비동기처리)  (0) 2022.04.28
*64일차 (정규표현식2)  (0) 2022.04.27
*63일차 (Event / 정규표현식)  (0) 2022.04.26