选择不更改的复选框文本

时间:2016-07-14 17:51:07

标签: javascript jquery html checkbox

以下是我的代码。选中复选框时,文本不会更改。 复选框的文本应该更改,但不是。

<html>
<head>
<title>OX</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$('#checkbox1').on('change', function () {
        window.alert(5 + 6);
    if ($('#checkbox1').is(':checked')) {
          window.alert(5 + 6);
        $("#description").html("Your Checked 1");

    } else {
        $("#description").html("No check");
    }
});

</script>
</head>
<body>

<input type="checkbox" value="0" id="checkbox1" name=""/> Answer one <br/></input>
<span id="description"> Hi Your Text will come here </span>   
</body>
</html>

2 个答案:

答案 0 :(得分:0)

使用尝试在正文标记结束之前加载Jquery和大多数其他JS frameworks,并用于绑定Jquery函数中的所有$(document).ready代码

编辑代码:

<html>
<head>
<title>OX</title>
</head>
<body>

<input type="checkbox" value="0" id="checkbox1" name=""/> 
<label for="">Answer one</label> <br/>

<span id="description"> Hi Your Text will come here </span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#checkbox1').on('change', function () {
        window.alert(5 + 6);
        if ($('#checkbox1').is(':checked')) {
              window.alert(5 + 6);
            $("#description").html("Your Checked 1");

        } else {
            $("#description").html("No check");
        }
    });
});

</script>

</body>
</html>

答案 1 :(得分:0)

正在发生的是您的脚本在加载DOM之前尝试运行。你怎么能找到一个甚至没有加载到页面上的复选框。简单的解决方案是使用document.ready处理程序,例如$( document ).ready(),这将允许您这样做。

我有一个工作示例,下面添加了此代码。跑吧看看。

<html>

<head>
  <title>OX</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#checkbox1').on('change', function() {
        window.alert(5 + 6);
        if ($('#checkbox1').is(':checked')) {
          window.alert(5 + 6);
          $("#description").html("Your Checked 1");

        } else {
          $("#description").html("No check");
        }
      });
    });
  </script>
</head>

<body>

  <input type="checkbox" value="0" id="checkbox1" name="" />Answer one
  <br/>
  </input>
  <span id="description"> Hi Your Text will come here </span> 
</body>

</html>

相关问题