如何使用 jQuery 更改点击时的图像源?
我目前正在构建完整的背景图像布局,我想根据用户正在访问的页面更改图像。言归正传:当用户单击链接时,我需要更改图像属性。这就是我走了多远:
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
});
});
<a href="" title="Switch" class="menulink">switch me</a>
<img src="img/picture2.jpg" id="bg" />
谢谢,可能很简单,但超出了我的想象!
I 'm currently building a full background image layout and I want to change the image based on which page the user is visiting. To get to the point: I need to change a images attribute when the user clickes on a link. This is how far I got:
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
});
});
<a href="" title="Switch" class="menulink">switch me</a>
<img src="img/picture2.jpg" id="bg" />
Thank you, probably easy stuff, but over my head!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它会切换回来,因为默认情况下,当您单击链接时,它会跟随该链接并加载页面。
就你而言,你不希望这样。您可以通过执行 e.preventDefault(); 来阻止它(就像 Neal 提到的)或通过返回 false :
关于之间差异的有趣问题防止默认并返回 false。
在这种情况下, return false 就可以正常工作,因为事件不需要传播。
It switches back because by default, when you click a link, it follows the link and loads the page.
In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :
Interesting question on the differences between prevent default and return false.
In this case, return false will work just fine because the event doesn't need to be propagated.
您需要使用
preventDefault()
来实现,这样当您单击它时链接就不会通过:fiddle: http://jsfiddle.net/maniator/Sevdm/
You need to use
preventDefault()
to make it so the link does not go through when u click on it:fiddle: http://jsfiddle.net/maniator/Sevdm/
您应该考虑为此使用按钮。链接通常应该用于链接。按钮可用于您想要添加的其他功能。尼尔斯解决方案有效,但它是一种解决方法。
如果您使用
You should consider using a button for this. Links generally should be use for linking. Buttons can be used for other functionality you wish to add. Neals solution works, but its a workaround.
If you use a
<button>
instead of a<a>
, your original code should work as expected.您可以使用 jQuery 的
attr()
函数,例如$("#id").attr('src',"source")
。You can use jQuery's
attr()
function, like$("#id").attr('src',"source")
.当您单击文本或链接时,图像将更改为另一个图像,因此您可以使用以下脚本帮助您在单击链接时更改图像:
css:
When you click the text or link the image will be changed to another image so you can use the below script helps to you to change image on click the link:
css: