我已经给元素“ characterImage”赋予了ID标签,但是javascript似乎并没有意识到我已经给它赋予了ID,即使我使用了element.id = "desiredID"
。
firefox webConsole只会不断返回document.getElementById(..)
为空”,即使我已经明确设置了一个ID并将其放在花括号中
我已经尝试了setAttributeAs()
方法和element.id = "desiredID"
{
let characterImage = document.createElement("IMG");
characterImage.id = "characterImg";
characterImage.src = "Story Game Photos";
characterImage.style.height = "250px";
characterImage.style.height = "250px";
}
function henryFunction(){
document.getElementById("characterImg").src = "Story Game photos/h.jpg";
document.getElementById("characterImg").appendChild(divCharacterImage);
}
我收到的错误消息:
TypeError:document.getElementById(...)为空
预期结果:让javascript识别ID并将我所需的图片放在所需的位置
答案 0 :(得分:4)
您必须将image element
附加到文档中的元素。如果元素存在于DOM
中,则可以使用id
并使用
document.getElementById()
添加行
document.querySelector("body").appendChild(characterImage)
将元素附加到body标签
function a(){
let characterImage = document.createElement("IMG");
characterImage.id = "characterImg";
characterImage.src = "Story Game Photos";
characterImage.style.height = "250px";
characterImage.style.height = "250px";
document.querySelector("body").appendChild(characterImage)
henryFunction();
}
function henryFunction(){
document.getElementById("characterImg").src = "https://placekitten.com/g/200/300";
}
a();
<html>
<body>
</body>
</html>
答案 1 :(得分:0)
从dom
访问它之前,必须将其附加到父项。
因此,在主要功能中运行.appendChild(divCharacterImage);
之前,请使用henryFunction();
。
function a(){
let characterImage = document.createElement("IMG");
characterImage.id = "characterImg";
characterImage.src = "Story Game Photos";
characterImage.style.height = "250px";
characterImage.style.height = "250px";
document.querySelector("body").appendChild(characterImage)
document.getElementById("characterImg").appendChild(divCharacterImage);
henryFunction();
}
function henryFunction(){
document.getElementById("characterImg").src = "Story Game photos/h.jpg";
}
只需检查此更新即可。