Javascript - 更改指定元素中元素的 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17774465/
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
Javascript - Change element's src in specified element
提问by Kyrtap
In html I have a lot od DIVs with names(yes, names, not IDs) respectively p001, p002, p003... which are like this:
在 html 中,我有很多带有名称(是的,名称,而不是 ID)的 od DIV,分别是 p001、p002、p003...,它们是这样的:
<div id="pole" name="p001"><img src=""></div>
<div id="pole" name="p002"><img src=""></div>
<div id="pole" name="p003"><img src=""></div>
etc...
等等...
In Javascript I have defined variable called 'pos' which contains a number, for now: "284" and a function which should change img src to "player.png". I tried 2 ways and none of these work:
在 Javascript 中,我定义了一个名为“pos”的变量,它包含一个数字,现在:“284”和一个应该将 img src 更改为“player.png”的函数。我尝试了两种方法,但这些方法都不起作用:
document.getElementsByName('p'+pos).innerHTML='<img src="player.png">';
and
和
document.getElementsByName('p'+pos).getElementsByTagName("img").src="player.png";
How to change img src which is in specified DIV?
如何更改指定DIV中的img src?
回答by Esailija
getElementsByName
returns a list of elements, not a single element, so try:
getElementsByName
返回元素列表,而不是单个元素,因此请尝试:
document.getElementsByName('p'+pos)[0].
getElementsByTagName("img")[0].src="player.png";
回答by mohkhan
First of all, I think you should switch name
and id
attributes on your div
tags. You CANNOT have multiple elements with the same id but you can have multiple elements with the same name.
首先,我认为您应该在标签上切换name
和id
属性div
。您不能有多个具有相同 id 的元素,但可以有多个具有相同名称的元素。
<div name="pole" id="p001"><img src=""></div>
<div name="pole" id="p002"><img src=""></div>
<div name="pole" id="p003"><img src=""></div>
To solve your problem you can use the firstChild
property of DOM if the img
will always be the first child of your div tag.
要解决您的问题,您可以使用firstChild
DOM的属性,如果 DOMimg
将始终是您的 div 标签的第一个孩子。
document.getElementById('p'+pos).firstChild.src="player.png";