为什么我的jQuery不能存在?

时间:2016-12-01 19:37:14

标签: jquery

我有这个jQuery脚本。当我选中snow[enabled]复选框时,它不显示#overlay div,live。它只检查页面加载...

(function( $ ) {
    $(function() {
        $('.color-field').wpColorPicker();
        $('#TB_window').draggable();
    });
    $(function() {
        if ($("#image-url").filter(function() { return $(this).val(); }).length > 0) {
            $("#has-image").show();
        }
        if(document.getElementById('snow[enabled]').checked) {
            $("#overlay").show();
        } else {
            $("#overlay").hide();
        }
    });
})( jQuery );

我怎样才能让这个活着?因此,即使在页面加载检查后是否选中snow[enabled],如果是,则显示div?

2 个答案:

答案 0 :(得分:1)

您需要将onchange事件绑定到复选框。

然后您可以简单地切换叠加层。

$('input#snow').on('change', function () {
    $("#overlay").toggle();
});

OR

您可以使用if else条件,具体取决于是否选中该复选框,以获得更可靠的结果。

$('input#snow').change(function () {
    if ($(this).prop("checked")) {
        $("#overlay").show();
    } else {
        $("#overlay").hide();
    }
});

答案 1 :(得分:0)

查看jQuery API中:checked选择器的示例,其中显示了如何在复选框的click事件上绑定函数,以查看它是已选中还是未选中。

https://api.jquery.com/checked-selector/

<script>
var countChecked = function() {
  var n = $( "input:checked" ).length;
  $( "div" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();

$( "input[type=checkbox]" ).on( "click", countChecked );
</script>