我的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>

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

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


当前回答

这是在Vanilla(或简单的Pure)JavaScript中完成任务的保证方法:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

其他回答

如果您多次更新图像,它会被缓存不更新,在末尾添加一个随机字符串:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

当改变图像源时,人们会犯的一个常见错误是不等待图像加载来执行后续操作,如成熟的图像大小等。在图像加载之后,您需要使用jQuery.load()方法来执行操作。

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

编辑原因:https://stackoverflow.com/a/670433/561545

您也可以通过以下方式使用jQuery执行此操作:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

如果图像源有多个状态,则可以有一个条件。

这是在Vanilla(或简单的Pure)JavaScript中完成任务的保证方法:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

只是一个补充,使其更为微小:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});