将图片添加到页面onclick [英] Add image to page onclick

查看:109
本文介绍了将图片添加到页面onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次单击按钮时都可以将图像添加到当前页面.例如,第一次打开页面时,只有一张图片.然后,您单击按钮,页面上将显示同一张图片,现在您拥有两张相同的图片.然后,您继续按下按钮,就会出现越来越多的相同图片.这是我尝试的无效代码:

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>

请帮助!谢谢.

推荐答案

您可能应该知道javascript可以创建html元素,但不能直接将html嵌入javascript(它们是两个完全独立的事物,具有不同的语法和关键字).因此,仅包含html的函数是无效的-您需要创建所需的元素,然后将其附加到所需的dom元素中.在这种情况下,您将创建一个新图像,然后将其附加到正文中.

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>

这篇关于将图片添加到页面onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆