如何在JavaScript中附加图像?

时间:2017-09-26 01:42:26

标签: javascript html

我对javascript很新,所以如果这是一个愚蠢的问题,我道歉。我正在尝试编写一个函数,它会在元素旁边添加某个图像,具体取决于它是真还是假。当我说src.appendChild(CorrectImg)时,我收到错误,它说“无法读取属性appendChild of null ...”

function check(bool, id) {
  var CorrectImg = document.createElement("CorrectImg");
  CorrectImg.src = "correct.png"
  var WrongImg = document.createElement("WrongImg");
  WrongImg.src = "wrong.png";

  if (bool) {
    var src = document.getElementById(id);
    src.appendChild(CorrectImg);
    return;
  }

  var src = document.getElementById(id);
  src.appendChild(WrongImg);
 }

2 个答案:

答案 0 :(得分:0)



function check(bool, id){
 var CorrectImg = document.createElement("img");
 CorrectImg.src = "correct.png"
 var WrongImg = document.createElement("img");
 WrongImg.src = "wrong.png";


 if(bool){
    var src = document.getElementById(id);
    src.appendChild(CorrectImg);
    return;
 }

 else{

    var src = document.getElementById(id);
    src.appendChild(WrongImg);
    return;
      }
 }




答案 1 :(得分:0)

这里的主要问题是你没有创建img元素。查看document.createElement()的文档,您将看到第一个参数应该是您要创建的HTML元素的名称。

所以你的代码:

var CorrectImg = document.createElement("CorrectImg");
 CorrectImg.src = "correct.png"
 var WrongImg = document.createElement("WrongImg");
 WrongImg.src = "wrong.png";

实际应该是:

var CorrectImg = document.createElement("img");
CorrectImg.src = "correct.png"
var WrongImg = document.createElement("img");
WrongImg.src = "wrong.png";