选中复选框时使用 javascript 和 html 显示图像 [英] Using javascript and html to show images when checkboxes are checked

查看:15
本文介绍了选中复选框时使用 javascript 和 html 显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个页面,该页面可根据用户单击的复选框生成简单的自定义报告.在左侧,我将有一个垂直的复选框列.为简单起见,假设我有两个标记为人口"和就业"的复选框.

I'm trying to create a page that generates simple custom reports based on the checkboxes a user clicks. On the left side I will have a vertical column of checkboxes. For simplicity's sake, lets say I have two checkboxes labeled "Population" and "Employment".

当用户有兴趣查看就业数据时,他们选中就业"框,数据的图像文件employment.jpg"将显示在右侧.如果他们随后取消选中该框,图像将消失.如果他们选中这两个复选框,则两个图像的显示方式类似,按照点击的顺序一个在另一个下方.

When a user is interested in seeing employment data they check the "Employment" box and the image file of the data "employment.jpg" will be displayed to the right. If they then uncheck the box, the image will disappear. If they check both boxes, both images will be similarly displayed, one below the other in the order clicked.

我对 HTML 不太熟悉,对 Javascript 不熟悉.我一直在尝试使用 if 语句和 document.write 来执行此操作,但是在生成图像时无法将复选框保留在页面上.

I'm am loosely familiar with HTML, and new to Javascript. I've been trying to do this with if statements and document.write but can't keep my checkboxes on the page when the image is generated.

这是我当前的代码:

<html>
    <head>
        <script language="javascript" type="text/javascript">
        function checker(that) {
            if (that.checked) {
                document.write("<br /><br /><img src='employment.png'>");
            }
        }
        </script>
    </head>
    <body>
        <form>
            <input type="checkbox" name="Box" onclick="checker(this)"> Employment <br />
        </form>
    </body>
</html>

推荐答案

这里有一个快速示例,可以帮助您入门.你可以在这里看到它的实际效果.

Here's a quick example to get you started. You can see it in action here.

function toggleVisibility(id) {
   var el = document.getElementById(id);

   if (el.style.visibility=="visible") {
          el.style.visibility="hidden";
     }
     else {
          el.style.visibility="visible";
     }
 }

<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>


<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation"  onChange="toggleVisibility('imgpopulation');" />
<hr />

<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG"  style="visibility:hidden"/>
<img id="imgpopulation" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG"  style="visibility:hidden" />

这篇关于选中复选框时使用 javascript 和 html 显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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