Home >Web Front-end >JS Tutorial >How Can I Dynamically Change Image Sources with jQuery on Click?

How Can I Dynamically Change Image Sources with jQuery on Click?

DDD
DDDOriginal
2024-12-20 19:16:11275browse

How Can I Dynamically Change Image Sources with jQuery on Click?

Modifying Image Sources with jQuery

Your objective is to dynamically alter image sources within the following DOM structure:

<div>

Upon clicking each image, you desire to alter its source to "imgx_off.gif," where "x" corresponds to either "1" or "2."

Solution: Leveraging jQuery's attr() Function

Yes, it's feasible to accomplish this without CSS. jQuery's attr() method enables you to modify DOM element attributes, including image source URLs.

For instance, if your image tag posiada an id attribute of "my_image," the following code will do the trick:

<img>
$('#my_image').attr("src", "second.jpg");

To attach this action to a click event:

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

Image Rotation

If you want to rotate the images, use this code:

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

The above is the detailed content of How Can I Dynamically Change Image Sources with jQuery on Click?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn