Javascript 使用javascript添加图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5865790/
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-23 19:15:47  来源:igfitidea点击:

Adding image using javascript

javascript

提问by Durga Dutt

I have a html page in which there is an image in anchor tag code is :

我有一个 html 页面,其中锚标记代码中有一个图像:

<a href="www.google.com" id="x"><img src="images/test.png" /></a>

on body onload event i am calling a javascript function which dynamically changes the image . My code is:

在 body onload 事件上,我正在调用一个动态更改图像的 javascript 函数。我的代码是:

<script type="text/javascript">
function changeImage()
{
  document.getElementById('x').innerHTML= '<img src="images/test2.png" />'; 
}
</script>

This is working fine in firefox but not working in google chrome and ie. Please help..

这在 Firefox 中运行良好,但在 google chrome 和 ie 中不起作用。请帮忙..

回答by Harry Joy

try this:

尝试这个:

<a href="www.google.com" id="x"><img id="y" src="images/test.png" /></a>

in js

在js中

function changingImg(){
    document.getElementById("y").src="./images/test2.png"
}


Tested in Chrome and IE.

在 Chrome 和 IE 中测试。



Then try this: [hoping that id of <a>is available and have at least one img tag]

然后试试这个:[希望 id<a>可用并且至少有一个 img 标签]

var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";

回答by Anil Namde

try following instead of changing innerHTML.

尝试遵循而不是更改innerHTML。

function changeImage()
{
  var parent = documeent.getElementById('x');
  parent.getElementsByTagName("img")[0].src = "newUrl";
}

回答by RobG

As others have indicated, there are many ways to do this. The A element isn't an anchor, it's a link. And no one really uses XHTML on the web so get rid of the XML-style syntax.

正如其他人所指出的,有很多方法可以做到这一点。A 元素不是锚点,而是链接。并且没有人真正在 Web 上使用 XHTML,因此摆脱 XML 样式的语法。

If you don't have an id for the image, then consider:

如果您没有图像的 id,请考虑:

function changeImage(id, src) {

  var image;
  var el = document.getElementById(id);

  if (el) {
    image = el.getElementsByTagName('img')[0];

    if (image) {
      image.src = src;
    }
  }
}

Then you can use an onload listener:

然后你可以使用一个 onload 监听器:

<body onload="changeImage('x', 'images/test.png');" ...>

or add a script element after the link (say just before the closing body tag) or use some other strategy for running the function afterthe image is in the document.

或者在链接之后添加一个脚本元素(比如刚好在结束正文标签之前),或者在图像出现在文档中之后使用其他一些策略来运行该函数。