【问题标题】:jQuery + Multiple Checkboxes: Show div on checked, Hide on uncheckjQuery + 多个复选框:选中时显示 div,取消选中时隐藏
【发布时间】:2011-02-21 09:08:37
【问题描述】:

我从 PHP 脚本中生成了多个复选框。

<input type="checkbox" class="checkbox" name="item[]" value="1" />

<input type="checkbox" class="checkbox" name="item[]" value="2" />

<input type="checkbox" class="checkbox" name="item[]" value="3" />

<input type="checkbox" class="checkbox" name="item[]" value="4" />

现在,一旦选中了一个复选框 - 我想显示一个带有“删除选定项”之类的选项的 div。但是,在取消选中所有复选框后,DIV 应该会再次消失。 我有以下代码,但它没有隐藏 DIV。

    $(".checkbox").live('click', function () {

        countChecked () ;

        if (countChecked() == "1" ) {

            $("div#options").fadeOut("medium") ;

        } else {

            if ( $("div#options").is(":hidden") ) {

                $("div#options").fadeIn ( "medium" ) ;

            }

        }

    });

另外,“countChecked”函数如下所示。

    function countChecked() {

        var n = $("input.checkbox:checked").length;

    }

【问题讨论】:

  • 首先你的函数没有返回任何东西

标签: jquery animation checkbox


【解决方案1】:

你的函数应该返回值:

function countChecked() {
    return $("input.checkbox:checked").length;
}

如果要检查金额是否为0,也可以删除对countChecked的重复调用

$(".checkbox").live('click', function () {
    if (countChecked() == 0 ) {

【讨论】:

  • @Roel,如果你只是想检查是否有检查,你可以将函数简化为return !!$("input.checkbox:checked").length;。当length为0时,返回false,否则返回true。 :) 这样你的 if 语句就只是 if (countChecked()) { } else { }
【解决方案2】:

在您的 countChecked()-函数中,使用 return 语句..

 function countChecked() {

        var n = $("input.checkbox:checked").length;
        return n;

    }

点击复选框时...

 $(".checkbox").live('click', function () {

        if (countChecked() == 0 ) {

            $("div#options").fadeOut("medium") ;

        } else {

            if ( $("div#options").is(":hidden") ) {

                $("div#options").fadeIn ( "medium" ) ;

            }

        }

    });

【讨论】:

    【解决方案3】:

    你可以使用

    $('.checkbox').live('click',function(){
        // if you just checked the current one, no need to check the rest
        if (this.checked)
        {
          $('#options').fadeIn('medium');
        }
        else // if you just unchecked
        {
            if ( !$('.checkbox:checked').length ) // check the whole group
            {
                $('#options').fadeOut('medium');
            }
        }
    });
    

    演示地址 http://jsfiddle.net/gaby/wZWbS/

    【讨论】:

      【解决方案4】:

      【讨论】:

        【解决方案5】:

        另一个版本,优化很小:http://jsfiddle.net/Briganti/XNWEP/

        玩得开心:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-01-23
          • 1970-01-01
          • 1970-01-01
          • 2015-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多