我正在尝试根据复选框显示/隐藏 html 表单的一部分。这是我的本质代码:
<script src="/js/jquery.js"></script>
<script language="JavaScript">
function toggle(className){
var $input = $(this);
if($(this).prop('checked'))
$(className).show();
else
$(className).hide();
}
</script>
<fieldset><legend>Check Here
<input type="checkbox" onclick="toggle('.myClass')" ></legend>
<span class="myClass">
<p>This is the text.</p>
</span>
</fieldset>
当您点击复选框时,span 会隐藏并且不会再出现。我还使用了 $(this).is(':checked')
。看起来 $(this).prop('checked')
评估为 false 无论它是否被选中。我最好的猜测是我错误地使用了 $(this)
。我在这里缺少什么?
最佳答案
HTML,从点击事件中传递this
<input type="checkbox" onclick="toggle('.myClass', this)" ></legend>
JS
function toggle(className, obj) {
var $input = $(obj);
if ($input.prop('checked')) $(className).hide();
else $(className).show();
}
或者,不使用 prop
你可以这样做:
function toggle(className, obj) {
if ( obj.checked ) $(className).hide();
else $(className).show();
}
或者,在一行中使用 .toggle( display )
:
function toggle(className, obj) {
$(className).toggle( !obj.checked )
}
关于javascript - 使用 jQuery 显示/隐藏复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15766875/