如何使用jQuery更改图片来源? [英] How can I change image source on click with jQuery?
问题描述
我当前正在构建完整的背景图像布局,并且我想根据用户正在访问的页面来更改图像.要指出重点:当用户单击链接时,我需要更改images属性.这是我走了多远:
$(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" />
谢谢你,也许很简单,但是让我头疼!
它会切换回去,因为默认情况下,当您单击链接时,它将跟随该链接并加载页面. 就您而言,您不想要那样.您可以通过执行e.preventDefault();来防止这种情况. (例如提到的Neal)或返回false:
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
在这种情况下,因为不需要传播事件,所以返回false可以正常工作.
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!
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 :
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return 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.
这篇关于如何使用jQuery更改图片来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!