Javascript JQuery 通过 ID 更改 <img src="" 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9046487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:29:04  来源:igfitidea点击:

JQuery change the value of an <img src="" by ID

javascriptjquery

提问by Satch3000

I need some simple JQuery code so I can change the src value of a specific img.

我需要一些简单的 JQuery 代码,以便更改特定 img 的 src 值。

It's currently:

目前是:

<img id="myImage" src="image1.gif" />

and I need to change it to:

我需要将其更改为:

<img id="myImage" src="image2.gif" />

using JQuery.

使用 JQuery。

回答by Yves Lange

Using: $(function(){ ... });

使用: $(function(){ ... });

You can use:

您可以使用:

$('#id').attr('src', 'newImage.jpg');

to change the image source immediately.

立即更改图像源。



Alternatively, you can use jQuery animations to change an image.

或者,您可以使用 jQuery 动画来更改图像。

JS

JS

$("#id1").fadeOut();
$("#id2").delay(200).fadeIn();

HTML

HTML

<div>
    <img id='id1' src='one.jpg'>
    <img id='id2' src='two.jpg'>
</div>

(Don't forget to change the CSS of #id2and put display: noneas initial state).

(不要忘记更改 CSS#id2并将其display: none作为初始状态)。

回答by mreq

That's elementary, use jQuery attr...

这是基本的,使用 jQuery attr...

$('img#myImage').attr('src', 'image2.gif');

回答by Darin Dimitrov

You could use the .attr()function to set attributes on given DOM element:

您可以使用该.attr()函数来设置给定 DOM 元素的属性:

$(function() {
    $('#myImage').attr('src', 'image2.gif');
});

回答by Jashwant

$('#myImage').attr('src','theothersrc.gif')

回答by Basic

$("#myImage").attr('src', 'image2.gif')