如果选中复选框,则显示隐藏内容 [英] show hide content depending if a checkbox is checked

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

问题描述

我对jquery很新,所以我为自己感到自豪的是我迄今为止找到的东西。我想要做的是显示/隐藏选项列表,取决于应用程序复选框的状态。 Eveything工作很好,但我不知道如何检查一个复选框是否检查加载我知道我应该能够使用 is.checked right现在我有了这个javascript

I'm pretty new to jquery so I'm proud of myself for what I've figured out so far. What I'm trying to do is show/hide a list of options depending on the approprate check box status. Eveything is working just fine but I can't figure out how to check to see if a check box is checked on load I know I should be able to use is.checked right now I have this javascript

    $('.wpbook_hidden').css({
    'display': 'none'
});
$(':checkbox').change(function() {
    var option = 'wpbook_option_' + $(this).attr('id');
    if ($('.' + option).css('display') == 'none') {
        $('.' + option).fadeIn();
    }
    else {
        $('.' + option).fadeOut();
    }
});

根据复选框的状态,类会淡入和淡出。这是我的html

Which fades in and out a class depending on the status of the checkbox. This is my html

<input type="checkbox" id="set_1" checked> click to show text1
<p class = "wpbook_hidden wpbook_option_set_1"> This is option one</p>
<p class = "wpbook_hidden wpbook_option_set_1"> This is another option one</p>
<input type="checkbox" id="set_2"> click to show text1
<p class = "wpbook_hidden wpbook_option_set_2"> This is option two</p>

我遇到的两个问题是内容与 .wpbook_hidden 类始终是隐藏的,并且如果在加载时选中复选框,则应加载内容。

The two problems I have are that the content with the .wpbook_hidden class is always hidden and if the checkbox is checked on load the content should load.

如果有人能知道如何检查在装载的箱子的状态,这将是很安慰的随意玩这个jfiddle http://jsfiddle.net/MH8e4/3/

If someone could figure out how to check the status of the box on load that would be much appriciated feel free to play with this jfiddle http://jsfiddle.net/MH8e4/3/

推荐答案

您可以使用:checked 作为选择器。像这样,

you can use :checked as a selector. like this,

alert($(':checkbox:checked').attr('id'));



更新小提示



或者如果您想检查特定复选框的状态,将会是这样

updated fiddle

or if you want to check the state of a particular checkbox, it would be something like this

alert($('#set_1')[0].checked);



更新小提示






下面的注释,我已编辑您的代码,现在看起来像这样。

updated fiddle


for the comment below, I have edited your code and now looks like this.

$('.wpbook_hidden').hide();

$(':checkbox').change(function() {
    changeCheck(this);
});

$(':checkbox:checked').each(function(){ // on page load, get the checked checkbox.
    changeCheck(this); // apply function same as what is in .change()
});

function changeCheck(x) {
    var option = 'wpbook_option_' + $(x).attr('id');
    if ($('.' + option).is(':visible')) { // I'm not sure about my if here.
        $('.' + option).fadeOut();        // if necessary try exchanging the fadeOut() and fadeIn()
    }
    else {
        $('.' + option).fadeIn();
    }
}

这篇关于如果选中复选框,则显示隐藏内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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