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

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

问题描述

我正在尝试根据复选框显示/隐藏 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,从点击事件传递this

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 显示/隐藏复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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