如果选中复选框,我该如何获取? [英] How do I get if a checkbox is checked or not?

查看:137
本文介绍了如果选中复选框,我该如何获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我的窗体不想得到复选框的值...我不知道它是否是我的编码,但是当我尝试和 alert()的值,我得到 undefined 作为结果。我错了什么?

For some reason, my form does not want to get the value of a checkbox... I am not sure if it is my coding or not, but when I try and alert() the value, I get undefined as a result. What do I have wrong?

<head>
  <script>
    var lfckv = document.getElementById("lifecheck").checked
    function exefunction(){
      alert(lfckv);
    }
  </script>
</head>
<body>
  <label><input id="lifecheck" type="checkbox" >Lives</label>
</body>

EDIT

我尝试将它改为

function exefunction() {
    alert(document.getElementById("lifecheck").checked);
}

但现在它甚至不想要 execute 。出现了什么问题?

But now it doesn't even want to execute. What's going wrong?

推荐答案

var lfckv 当执行该行时,主体尚未解析,并且元素lifecheck不存在。这完全正常:

Place the var lfckv inside the function. When that line is executed, the body isn't parsed yet and the element "lifecheck" doesn't exist. This works perfectly fine:

<html>
    <head>
        <script language="javascript" type="text/javascript">
            function exefunction(){
                var lfckv = document.getElementById("lifecheck").checked;
                alert(lfckv);
            }
        </script>
    </head>
    <body>
        <label><input id="lifecheck" type="checkbox" >Lives</label>
        <button onclick="exefunction()">Check value</button>
    </body>
</html>

这篇关于如果选中复选框,我该如何获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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