简体   繁体   English

使用jQuery检查加载时是否已选中复选框

[英]Check if checkbox is ALREADY checked on load using jQuery

I am currently using 我目前正在使用

 $("#some-box").click(function(){
     $("#main-box").toggle();
  });

Which works well, except for when the checkbox is part of a page that saves the checkboxes status. 除了复选框是保存复选框状态的页面的一部分之外,哪个效果很好。 If a checkbox is saved as ticked, the main-box (which is revealed when the checkbox is clicked) is hidden on reload, and is only visible if the checkbox is clicked, which in now would mean "unticked" checkbox (as expected with the toggle). 如果复选框保存为勾选,则主框(在单击复选框时显示)在重新加载时隐藏,仅在单击复选框时才可见,现在这意味着“未选中”复选框(如预期的那样)切换)。

How can I check on page load if the checkbox is already ticked, in which case to trigger the toggle automatically? 如果勾选了复选框,如何检查页面加载,在这种情况下是否自动触发切换?

this should work: 这应该工作:

if ($("#some-box").is(':checked')){
    $("#main-box").show();
}

You can get the initial state with .attr("checked") or .prop("defaultChecked") . 您可以使用.attr("checked").prop("defaultChecked")获取初始状态。 However, I think the following is a better way: 但是,我认为以下是更好的方法:

function update() {
    $("#main-box")[this.checked ? "hide" : "show"]();
    // as by @zerkms, this is a different way for writing it:
    // $("#main-box").toggle(this.checked);
}
update.call($("#some-box").click(update)[0]);

For most events it is easy to just trigger it once for initialisation, but that doesn't apply here - we don't want to click (and change) the checkbox automatically onload. 对于大多数事件,只需触发一次初始化即可,但这不适用于此 - 我们不希望自动点击(并更改)复选框。

.toggle() accepts the state - so you could pass whether to show or hide an element on a particular call: .toggle()接受状态 - 因此您可以传递是否在特定调用上显示或隐藏元素:

$("#some-box").change(function(){
     $("#main-box").toggle($(this).is(':checked'));
  });

$('#some-box').trigger('change');

PS: as you can see I'm proposing to use change event instead of click PS:你可以看到我建议使用change事件而不是click

Online demo: http://jsfiddle.net/R4Bjw/ 在线演示: http//jsfiddle.net/R4Bjw/

Use is(':checked') to test and show the box if the checkbox is checked: 如果选中该复选框,则使用is(':checked')测试并显示该框:

if ($('#some-box').is(':checked')) {
    $('#main-box').show();
}

And then use your click handler as-is. 然后按原样使用您的点击处理程序。

(function($) {
    var $somebox = $('#some-box'),
        $mainbox = $('#main-box');

    var toggleMain = function() {
        $mainbox.slideToggle();
    };

    if($somebox.is(':checked')) {
        toggleMain();
    }

    $somebox.on('click', toggleMain);
})(window.jQuery);

Here is a fiddle: http://jsfiddle.net/FX7Du/4/ 这是一个小提琴: http//jsfiddle.net/FX7Du/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM