使用jQuery显示/隐藏Checkbox [英] Show/Hide with Checkbox using jQuery

查看:620
本文介绍了使用jQuery显示/隐藏Checkbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据复选框显示/隐藏html表单的一部分。这是我的基本代码:

I am trying to have a section of an html form to show/hide based on a checkbox. This is the essence code I have:

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

单击复选框后,跨度将隐藏,不会再返回。我还使用了 $(this).is(':checked')。似乎 $(this).prop('checked')正在评估 false 是否已选中。我最好的猜测是我错误地使用 $(this)。我在这里缺少什么?

When you click on the checkbox, the span gets hidden and will not come back. I have also used $(this).is(':checked'). It appears that $(this).prop('checked') is evaluating to false whether it is checked or not. My best guess is that I am using $(this) incorrectly. What am I missing here?

推荐答案

HTML,传递来自点击事件

HTML, pass this from on click event

<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 你可以这么做:

OR, without using prop you can just do:

function toggle(className, obj) {
    if ( obj.checked ) $(className).hide();
    else $(className).show();
}

或者,在一行中使用 .toggle(display)

OR, in one-line using .toggle( display ):

function toggle(className, obj) {
    $(className).toggle( !obj.checked )
}

这篇关于使用jQuery显示/隐藏Checkbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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