我不知道为什么这段代码无法正常工作,但当我选中复选框时,它就无法工作。 div只是隐藏着。我之前已经这样做了,但这次它没有工作。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="WebPartPageExpansion" content="full" />
<meta charset="utf-8">
<title>jQuery Show Hide Using Checkboxes</title>
<script type="text/javascript" src="../SiteAssets/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var checked = $(this).attr('checked');
if (checked) {
$('.other').show();
} else {
$('.other').hide();
}
});
});
</script>
</head>
<body>
<div name="main">
<input type="checkbox" /> If this is checked display div
</div>
<div class='other' name='other' title='other' style='display:none;'>
<h2>test</h2>
<input></input>
<input></input>
<input></input>
</div>
</body>
</html>
我做错了什么?我无法解决这个问题。感谢。
答案 0 :(得分:1)
因为复选框中有无属性 checked
。所以它返回 undefined 。您可以通过this.checked
直接访问该属性。
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var checked = this.checked;
if (checked) {
$('.other').show();
} else {
$('.other').hide();
}
});
});
答案 1 :(得分:0)
您正在使用返回attr
undefined
var checked = $(this).attr('checked');
if (checked) { //here checked is not a boolean
永远记住
.prop('checked')
返回布尔值
因此请使用.prop()
。休息很好。
希望有所帮助:)