【问题标题】:Add image to page onclick将图像添加到页面 onclick
【发布时间】:2012-01-16 21:04:48
【问题描述】:

我想要一个按钮来在每次点击时将图像添加到当前页面。例如,第一次打开页面时,有一张图片。然后单击按钮,页面上会出现相同的图片,现在您有两张相同的图片。然后你继续按下按钮,越来越多的相同图片出现。这是我试过但不起作用的代码:

<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>

请帮忙!谢谢。

【问题讨论】:

    标签: image button onclick


    【解决方案1】:

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

    <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>
    

    【讨论】:

    • 谢谢!但是如何添加图像类?我试过 img.class 但没有用。
    • 我编辑了答案以展示如何为元素设置 css 类。希望这会有所帮助!
    • 由于某种原因,在我添加了类的东西后,按钮不起作用。我应该替换“class”或“foo”这个词吗?我使用的类是 box2d,如果有帮助的话。
    • 在上面的示例代码中,我在添加的图像上设置了一个名为“foo”的类。我将对其进行编辑以使其更加清晰。 setAttribute 方法有两个属性——属性的名称,然后是值。
    • 糟糕,我在 setAttribute 调用中引用了错误的变量。当我的变量命名为“img”时,我的代码是“image.setAttribute”。抱歉,如果这让您感到困惑。
    【解决方案2】:

    你所缺少的只是在页面上写入元素的方法

      <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>
    

    【讨论】:

    • 这实际上会使整个文档成为一个图像。您想附加到文档的正文中,这样您就可以继续添加图像,而不是替换已经存在的按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2016-07-30
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多