当至少选中页面上的一个复选框时,我使用这些脚本显示一个 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 显示)但随后又下定决心再次取消选中,我如何让 div #maak_deel 隐藏。现在什么也没有发生,我希望 div 再次消失。我试过切换,但效果不佳。
非常感谢您帮助我!
最佳答案
您可以在计数函数中包含隐藏和显示代码。
<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 的 $(document).ready(function(){//code goes here; }) 中结束,要么将代码包装起来
关于javascript - 选中至少一个复选框时显示一个 div,但取消选中最后一个复选框后隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27078814/