繁体   English   中英

jquery onclick切换图像src

[英]jquery onclick toggle image src

我把这段代码放在一起:

 $('img').on({ 'click': function() { var src = ($(this).attr('src') === 'memes/2a.png') ? 'memes/2b.png' : 'memes/2a.png'; $(this).attr('src', src); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <a href="#"><img id="img1" src="memes/2a.png" height="500" width="600"></a> 

它应该在两个图像之间切换:2a.png和2b.png当我点击它时没有任何反应。

有人能告诉我我做错了什么吗?

这里的主要问题是你的锚元素,它导致页面重新加载

只需删除锚元素并为图像指定光标

没有锚a ,光标在图像上

 $('img').on({ 'click': function() { document.querySelector('span').textContent = $(this).attr('src'); var src = ($(this).attr('src') === 'animals/5/') ? 'animals/6/' : 'animals/5/'; $(this).attr('src', src); } }); 
 #img1 { cursor: pointer; } span { vertical-align: top; padding: 5px 10px; background: black; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <base href="http://lorempixel.com/300/300/"> <img id="img1" src="animals/5/" height="300" width="300"> <span></span> 

使用锚点a ,这将无法正常工作

 $('img').on({ 'click': function() { document.querySelector('span').textContent = $(this).attr('src'); var src = ($(this).attr('src') === 'animals/5/') ? 'animals/6/' : 'animals/5/'; $(this).attr('src', src); } }); 
 span { vertical-align: top; padding: 5px 10px; background: black; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <base href="http://lorempixel.com/300/300/"> <a href="#"><img id="img1" src="animals/5/" height="300" width="300"></a> <span></span> 

另一个选择是取消事件冒泡,并保持锚点a ,但我仍然建议简单地删除它

 $('img').on({ 'click': function(e) { document.querySelector('span').textContent = $(this).attr('src'); var src = ($(this).attr('src') === 'animals/5/') ? 'animals/6/' : 'animals/5/'; $(this).attr('src', src); e.stopPropagation(); return false; } }); 
 span { vertical-align: top; padding: 5px 10px; background: black; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <base href="http://lorempixel.com/300/300/"> <a href="#"><img id="img1" src="animals/5/" height="300" width="300"></a> <span></span> 

正如其他人指出的那样,可能是因为相对路径问题。 如果您不想使用绝对路径,可以在图像上保留数据属性以了解如何处理切换。

 $('img').on({ 'click': function() { var i = $(this).attr('data-index'); switch (i) { case '0': i = '1'; src = 'https://unsplash.it/100/100?image=1'; break; case '1': default: i = '0'; src = 'https://unsplash.it/100/100?image=0'; break; } $(this) .attr('src', src) .attr('data-index', i); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <a href="#"> <img id="img1" data-index='1' src="https://unsplash.it/100/100?image=1"> </a> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM