2016-07-14 83 views
-2

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

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

你正在运行的代码之前存在的元素。查看$(document).ready,以便在dom准备就绪之前不会触发代码https://learn.jquery.com/using-jquery-core/document-ready/ –

+1

或..移动您的JS代码BELOW HTML – Zak

+0

另外,[''](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)是一个[“空元素”](https://开发者。 mozilla.org/en-US/docs/Glossary/empty_element),这意味着它不能包含任何子节点。我建议使用['

回答

0

使用尝试加载Jquery和大多数其他JS frameworks body标签结束前和使用绑定所有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> 
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>