2014-11-22 41 views
0

当至少选中页面上的一个复选框时,我使用这些脚本显示div。当至少选中一个复选框时显示div,但在最后一个复选框未选中后隐藏

在页面加载时,所有复选框都未被选中。如果用户检查一个,隐藏的div显示。 我为此使用了两个脚本。

最先发现这里http://api.jquery.com/checked-selector/

<script> 
var countChecked = function() { 
    var n = $("input:checked").length; 
    $("#count").text(n + (n === 1 ? " is" : " zijn") + " aangevinkt!"); 

}; 
countChecked(); 

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

第二个脚本显示了一个隐藏的div #maak_deel

<script> 
$("input[type=checkbox]").on("click", function() { 
    $("#maak_deel").fadeIn(); 
    }); 

</script> 

我有两个问题,由于这样的事实,我在这个新的。

1)我如何结合这二合一脚本(使我的代码更干净)

2)我怎样才能让DIV #maak_deel隐藏,如果用户检查一个(= DIV节目),但随后下定决心,不再检查。现在没有任何反应,我希望div再次消失。我试过切换,但是这会产生错误的效果。

非常感谢您的帮助!

回答

0

您可以在计数功能中包含隐藏和显示代码。

<script> 
var countChecked = function() { 
    var n = $("input:checked").length; //n now contains the number of checked elements. 
    $("#count").text(n + (n === 1 ? " is" : " zijn") + " aangevinkt!"); //show some text 
    if(n == 0){ 
    $("#maak_deel:visible").fadeOut(); //if there are none checked, hide only visible elements 
    } else { 
    $("#maak_deel:hidden").fadeIn(); //otherwise (some are selected) fadeIn - if the div is hidden. 
    } 

}; 
countChecked(); 

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

这必须是DOM之后执行当然被加载,所以无论是在结束时或在包裹jQuery的$(文件)的代码。就绪(函数(){//代码到这里;});

相关问题