使用jQuery更改图像源 [英] Changing the image source using jQuery

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

问题描述

我的DOM看起来像这样:

My DOM looks like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

当有人点击图片时,我希望图片src更改为 < img src =imgx_off.gif> 其中 x 表示图像编号1或2.

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

这是可能的还是我必须使用CSS来更改图像?

Is this possible or do I have to use CSS to change the images?

推荐答案

你可以使用jQuery的 attr()函数。例如,如果你的img标签的id属性为'my_image':

You can use jQuery's attr() function. For example, if you img tag has an id attribute of 'my_image':

<img id="my_image" src="first.jpg"/>

然后你可以通过以下方式更改jQuery中的src:

Then you can change the src in jQuery by:

$("#my_image").attr("src","second.jpg");

要将此附加到点击事件,你可以写:

To attach this to a click event, you could write:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

要旋转图像,您可以这样做:

To rotate the image, you could do this:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

这篇关于使用jQuery更改图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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