将图片添加到对象javascript

时间:2016-06-04 16:56:03

标签: javascript html

您好,这可能是一个愚蠢的问题,但我是javascript的初学者,当我点击按钮时图像不会出现它只是链接。 谢谢。

Y

2 个答案:

答案 0 :(得分:1)

试试这个:

function myfunc() {
  var apple = new fruit("Apple", "Red", "http://www.lifemartini.com/wp-content/uploads/2012/04/Apple-Fruit1.jpg");
  var banana = new fruit("Banana", "Yellow", "https://www.healthbytez.com/wp-content/uploads/2015/11/bana.jpg");
  document.getElementById("h31").innerHTML = apple.name;
  document.getElementById("p1").innerHTML = apple.colour;
  document.getElementById("p2").innerHTML = '<img src="' +apple.image+ '" />';
  document.getElementById("h32").innerHTML = banana.name;
  document.getElementById("p3").innerHTML = banana.colour;
  document.getElementById("p4").innerHTML = '<img src="' +banana.image+ '" />';
}

function fruit(name, colour, image) {
  this.name = name;
  this.colour = colour;
  this.image = image;
}
<button onclick="myfunc()" id="button" name="button">button</button>
<section class="box special features">
  <div class="features-row">
    <section>
      <h3 id="h31">&nbsp;</h3>
      <p id="p1">&nbsp;</p>
      <p id="p2">&nbsp;</p>
    </section>
    <section>
      <h3 id="h32">&nbsp;</h3>
      <p id="p3">&nbsp;</p>
      <p id="p4">&nbsp;</p>
    </section>
  </div>
</section>

答案 1 :(得分:1)

要以HTML格式显示图片,您应使用img标记及其src属性,如下所示:

HTML

<img id="zzz" />

JS

document.getElementById("zzz").src = apple.image;