如何更改图像链接

How to change image link onclick

本文关键字:链接 图像 何更改      更新时间:2023-09-26

我正在尝试更改点击链接的图像。

<div class="mobilestoreimg">
    <a href="/store-locator"><img src="../includes/mobile-location.png"/></a>
</div>
所以当你点击链接时图像就会从
mobile-location.png

mobile-location-blk.png

任何想法?

试试这个。这会对你很有帮助的。

如果你正在使用jQuery。

 $(function() {    
    $('.mobilestoreimg>a').click(function(event) {
      event.preventDefault();
      $('img').attr('src',"newValue");
    })
  })
否则

document.querySelector('.mobilestoreimg>a').addEventListener('click, function() {   this.querySelector('img').src = 'newValue'; }, false);

您可以为<img>元素添加ID,然后绑定onClick事件来更改src

<div class="mobilestoreimg">
    <a href="/store-locator"><img id="imgChange" src="../includes/mobile-location.png"/></a>
</div>

Javascript代码:

$('#imgChange').on('click', function(){
    $(this).attr('src','../includes/mobile-location-blk.png'); 
});

使用jQuery的替代版本:

  $(function() {    
    $('a').click(function(event) {
      event.preventDefault();
      $('img').attr('src',"newValue");
    })
  })

我做了一个jsfiddle,但网站不喜欢打断事件,无论如何,如果你想要它,它在这里,但没有链接在href: http://jsfiddle.net/g1z4zqt9/2/