如何使用jQuery根据保存的单选按钮选择加载隐藏的div?

如何使用jQuery根据保存的单选按钮选择加载隐藏的div?,jquery,Jquery,我有一个表单,用户可以保存并返回编辑。我在表单上有一个区域,根据用户对前面问题的回答切换div。如果回答为“是”,则应显示div。但是,如果用户返回表单并选择“是”,则div将保持隐藏状态 此处的工作示例: HTML: 演示: 我将您的代码压缩了一点: $(document).ready(function() { $('#details').hide(); $('.toggle').on('change',function(){ $('#details').to

我有一个表单,用户可以保存并返回编辑。我在表单上有一个区域,根据用户对前面问题的回答切换div。如果回答为“是”,则应显示div。但是,如果用户返回表单并选择“是”,则div将保持隐藏状态

此处的工作示例:

HTML:

演示:

我将您的代码压缩了一点:

$(document).ready(function() {
    $('#details').hide();

    $('.toggle').on('change',function(){
        $('#details').toggle($(this).val()); 
    });
});

我也对HTML做了一些更改(从第一个元素中删除了
checked=“checked”
,并将其添加到第二个元素中)。

这是因为您在
文档中显式隐藏了details div。ready

首先检查单选按钮的值

$(document).ready(function() {

    if($('.toggle:checked').val() != 1)
        $('#details').hide();

    ...

})

我只是想说,我制作了一个代码更少、效果更好的版本:

// Make sure the page is loaded before doing anything
$(document).ready(function() {
    // Makes sure that it shows the div correctly, and doesn't flip the effects
    if($('.toggle:checked').val() !== 1)
        // Hides the div
        $('#details').hide();

    // When there is a change in the selection
    $('.toggle').on('change', function() {
        // Hide or show the div, depending on the var showOrHide
        $(this).parent().next('#details').fadeToggle('slow');
    });
});

它也有很好的文档记录。:)

我不明白这里有什么问题?默认情况下,选中“是”,因此您需要取消选择它,然后再次选择它以显示div,但它似乎工作正常。。。我想真正的问题是用户如何返回表单?如果是通过后退按钮,则可能需要通过
$('.toggle').change()在页面加载时手动调用更改事件。如果只是返回到页面,那么您已经将prev值保存在某个地方,因此应该检查它是否是,如果是,再次在加载时手动调用更改。谢谢。如果选择了收音机(),则此选项有效,但如果问题尚未回答(),则如何?如果是这种情况,应该隐藏div。现在,如果选择onload,则不会显示div@迈克尔,对不起。试试看。选择器
.toggle
没有像我想的那样工作,所以这里有另一个选项。太好了。我唯一的问题是表单上有多个收音机,并且是根据类切换的。无法使用.toggle选择器执行此操作吗?请再次将选择器替换为
.toggle
$(document).ready(function() {

    if($('.toggle:checked').val() != 1)
        $('#details').hide();

    ...

})
// Make sure the page is loaded before doing anything
$(document).ready(function() {
    // Makes sure that it shows the div correctly, and doesn't flip the effects
    if($('.toggle:checked').val() !== 1)
        // Hides the div
        $('#details').hide();

    // When there is a change in the selection
    $('.toggle').on('change', function() {
        // Hide or show the div, depending on the var showOrHide
        $(this).parent().next('#details').fadeToggle('slow');
    });
});