Add image to page onclick

自古美人都是妖i 提交于 2019-12-11 02:49:18

问题


I want a button to add an image to the current page on each click. For example, the first time you open the page, there is one picture. Then you click the button and the same picture appears on the page and now you have two same pictures. Then you keep on pressing on the button and more and more same pictures appear. This is the code I tried that didn't work:

<script type="text/javascript">
        function addimage() {<img src="http://bricksplayground.webs.com/brick.PNG" height="50" width="100">}
    </script>
</head>
<body>
    <button onclick="addimage();">Click</button>
</body>
</html>

Please help! Thanks.


回答1:


You should probably know that javascript can create html elements, but you cannot directly embed html inside javascript (they are two completely separate things with different grammars and keywords). So it's not valid to have a function that only contains html -- you need to create the elements you want, and then append them to the dom elements that you want them to. In this case, you create a new image and then append it to the body.

<html>
<body>
<script type="text/javascript">
        function addimage() { 
          var img = document.createElement("img");
          img.src = "http://bricksplayground.webs.com/brick.PNG"; 
          img.height = 50; 
          img.width = 100;

          //optionally set a css class on the image
          var class_name = "foo";
          img.setAttribute("class", class_name);

          document.body.appendChild(img);
        }
</script>
</head>
<body>
    <button onclick="addimage();">Click</button>
</body>
</html>



回答2:


All you're missing is a method to write the element on the page

  <script type="text/javascript">
    function addimage() {
      document.write('<img src="http://bricksplayground.webs.com/brick.PNG" height="50" width="100">')
    }
  </script>
</head>
<body>
  <button onclick="addimage();">Click</button>
</body>


来源:https://stackoverflow.com/questions/8886248/add-image-to-page-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!