jquery点击更改图像 [英] Jquery change image on click

查看:116
本文介绍了jquery点击更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建完整的背景图片布局,并且想要根据用户访问的页面更改图片。为了说明问题:当用户点击链接时,我需要更改图片属性。这是我得到了多少:

  $(function(){
$('。menulink')。click (function(){
$(#bg)。attr('src',img / picture1.jpg);
});
});

 

 < a href =title =Switchclass =menulink>切换我< / a> 
< img src =img / picture2.jpgid =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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆