Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery更改图像源(Changing the image source using jQuery)

My DOM looks like this:

(我的DOM看起来像这样:)

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

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.

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

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

(这可能吗,还是我必须使用CSS来更改图像?)

  ask by user67033 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use jQuery's attr() function.

(您可以使用jQuery的attr()函数。)

For example, if your img tag has an id attribute of 'my_image', you would do this:

(例如,如果您的img标签的id属性为“ my_image”,则可以执行以下操作:)

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

Then you can change the src of your image with jQuery like this:

(然后您可以使用jQuery更改图像的src ,如下所示:)

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

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

(要将其附加到click事件,您可以编写:)

$('#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);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...