jquery li点击img src替换(不是切换)

时间:2018-02-26 06:10:26

标签: jquery image replace click src

$(function() {

  $("#gnb li a").on("click", function() {
    $(this).find("img").attr("src", $(this).find("img").attr("src").replace("normal.svg", "press.svg"));
  });
  //not working
});
#gnb {
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 49px;
  background-color: #fff;
  padding-bottom: 5px;
  border-top: 1px solid #ddd;
}

#gnb li {
  position: absolute;
  top: 0px;
  width: 20%;
}

#gnb li:nth-of-type(1) {
  left: 0%
}

#gnb li:nth-of-type(2) {
  left: 20%
}

#gnb li:nth-of-type(3) {
  left: 40%;
  top: -15px;
}

#gnb li:nth-of-type(3) img {
  background-color: #fff;
  border-radius: 100%;
  border: 1px solid #ddd;
  box-sizing: border-box;
}

#gnb li:nth-of-type(4) {
  left: 60%
}

#gnb li:nth-of-type(5) {
  left: 80%
}

#gnb li a {
  display: block;
  text-align: center;
  line-height: 49px;
}

#gnb li a img {
  vertical-align: middle;
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul id="gnb">
  <li>
    <a href="../contents/shops.html"><img src="../images/gnb_btn1_normal.svg" alt="coupon"></a>
  </li>
  <li>
    <a href="../contents/history.html"><img src="../images/gnb_btn2_normal.svg" alt="useage"></a>
  </li>
  <li class="home">
    <a href="../contents/meal_tickets.html"><img src="../images/gnb_home_normal.svg" alt="home"></a>
  </li>
  <li>
    <a href="../contents/settings.html"><img src="../images/gnb_btn3_normal.svg" alt="setting"></a>
  </li>
  <li>
    <a href="../contents/information.html"><img src="../images/gnb_btn4_normal.svg" alt="info"></a>
  </li>
</ul>

li&gt;点击,每个img src替换 - 我想要 但没有使用此代码。 有什么问题?

1 个答案:

答案 0 :(得分:0)

试试这个:

$('#gnb li a').on('click', function(e) {
    e.preventDefault();
    $(this).find('img').attr('src').replace('../images/gnb_btn2_normal.svg', '../images/gnb_btn2_press.svg'));
});

编辑: 添加了对href的支持

$('#gnb li a').on('click', function(e) {
    e.preventDefault();
    $(this).find('img').attr('src').replace('../images/gnb_btn2_normal.svg', '../images/gnb_btn2_press.svg'));
    $(this).attr('href', 'press'));
});