Divs All Visible at Page Opening(尽管有 jquery,在单选按钮单击时显示 div)

时间:2021-01-03 20:31:24

标签: html jquery checkbox radio-button visibility

我正在尝试做;单击复选框单选按钮时显示 div。我是用 jquery 做的,但是当你加载页面时,我所有的 div 都是可见的。您必须单击我的第一个复选框单选按钮才能使其他 div 不可见。或者只需点击其他复选框单选按钮。

我试过了

#row2 {
display:none;

}

但是当我将其添加到 css 时,如果您单击第一个复选框单选按钮(与 div row2 相关),div 不可见,并且无法正常工作。

打开页面时的任何其他解决方案我只想看到已选中的 div (row2)。我不想在页面加载时看到其他 div。

谢谢...

演示链接:https://rexin-demo.netlify.app/main.html

Ps:图片和按钮在 jsfiddled 的资产上不可见。最好通过演示链接查看。

https://jsfiddle.net/t4e13xvj/

1 个答案:

答案 0 :(得分:1)

通过在输入的点击事件末尾添加 .filter(':checked').click() 来触发点击.. 试试吧

$(document).ready(function(){
    $('input[type="radio"]').click(function(){
        var inputValue = $(this).val(); // use .val() instead of .attr('value')
        var targetBox = $("." + inputValue);
        $(".box").not(targetBox).hide();
        $(targetBox).show();
    }).filter(':checked').click();
});

此外,我更喜欢使用 change 而不是 click 来输入单选框和复选框

$(document).ready(function(){
    $('input[type="radio"]').on('change' ,function(){
        if(this.checked){
          var inputValue = $(this).val();
          var targetBox = $("." + inputValue);
          $(".box").not(targetBox).hide();
          $(targetBox).show();
        }
    }).filter(':checked').prop('checked' , true).change();
 });

OR 只能使用 css

.box:not(.product){
  display : none;
}
相关问题