본문 바로가기

대돌이의 하루/PUBLISHING

jquery 이미지 attr img on off

ㅁ on일경우 off로 / off 일경우 on으로

$(this)
    .find("img")
    .attr("src", function(index, attr) {
      if (attr.match("on")) {
        return attr.replace("on", "off");
      } else {
        return attr.replace("off", "on");
      }
    });
    
    
    
    // 추가 예시
    
    $(".hot-deal__itemlist ul li .btn .ic_like").click(function() {
      $(this)
        .find("img")
        .attr("src", function(index, attr) {
          if (attr.match("thin-grey")) {
            return attr.replace("thin-grey", "purple");
          } else {
            return attr.replace("purple", "thin-grey");
          }
        });
	});

 

ㅁ단편적으로 이미지를 바꾸는 방법들

 //이미지 - 기존것지우기
    $(".vote__tab-left.exception2 ul li.btn__item--2")
      .find("img")
      .attr("src", "img/ic_tab-new_off.svg");

    // 이미지 - 클릭시 변경
    $(".vote__tab-left.exception2 ul li.btn__item--1")
      .find("img")
      .attr(
        "src",
        $(this)
          .find("img")
          .attr("src")
          .replace("_off.svg", "_on.svg")
      );