2

我有一个复选框。当它被选中时,会出现一个段落。当它未选中时,它会隐藏。没有问题。问题是:如果我选中复选框,当我按下 F5(刷新)按钮时,复选框仍然被选中,但段落被隐藏。我想在刷新页面时显示段落。

这是HTML:

<input type="checkbox" id="something">
<p id="info" style="display:none">Yes ,checkbox is checked now...</p>

这是jQuery:

$(document).ready(function() {

    $("#something").change( function(){
        if( $(this).is(':checked') ) {
            $("#info").show();
        } else {
            $("#info").hide();
        }
    });
});
4

5 回答 5

3

You should check the state of the checkbox at loading :

$(document).ready(function() {
    function f() {
       if( $('#something').is(':checked') ) {
            $("#info").show();
        } else {
            $("#info").hide();
        }
    }
    $("#something").change(f);
    f();
});
于 2012-11-09T13:15:52.443 回答
2

You just have to trigger the event

$(document).ready(function() {

    // this only runs upon the event
    $("#something").change( function(){
        if( $(this).is(':checked') ) {
            $("#info").show();
        } else {
            $("#info").hide();
        }
    });

    // trigger the event
    $("#something").trigger("change");
});
于 2012-11-09T13:16:31.537 回答
1

Your current behavior is because you have the event handler for change. So when you do F5 and refresh, even though it is checked, there is no change.

You can just call this function explicitly in document.ready

function SetParagraphStatus() {
    if ($(this).is(':checked')) {
        $("#info").show();
    } else {
        $("#info").hide();
    }
}

$(document).ready(function () {

    $("#something").change(SetParagraphStatus);
    // call it anyway for load.
    SetParagraphStatus();
});
于 2012-11-09T13:17:26.530 回答
1

只需触发更改事件。

$(document).ready(function() {
    $("#something").change(function(){
        $("#info").toggle(this.checked);
    }).change()
})
于 2012-11-09T13:20:09.237 回答
0
$(window).bind("beforeunload", function(){

    $("#something >#info").show();

});
于 2014-08-28T21:15:33.253 回答