如何使用多个复选框 return 单个 div

How to use multiple checkboxes to return a single div

我正在处理一个包含多个复选框的页面,并且希望它 return 一个基于任何检查组合的 div。我创建了一个 jsfiddle,但尽管这是我网站上的代码,但它在 jsfiddle 上不起作用:

HTML:

<div id="checkboxes">
<input type="checkbox" id="red" name="color">Red
<input type="checkbox" id="blue" name="color">Blue
<input type="checkbox" id="green" name="color">Green
</div>

<br /><br />
<div id="default" style="display:none;">Show this by default</div><br />
<div id="showred" style="display:none;">This is red</div><br />
<div id="showblue" style="display:none;">This is blue</div><br />
<div id="showgreen" style="display:none;">This is green</div><br />
<div id="showpurple" style="display:none;">This is purple</div>

JS:

$(document).ready(function() {
var r = $('#red');
var b = $('#blue');
var g = $('#green');
var p = r.add(b);

$(r).click(function(){
    if ($(r).is(':not(:checked)')) {
        $('#showred').show();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').hide();
    } else {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').show();
    }
});

$(b).click(function(){
    if ($(b).is(':not(:checked)')) {
        $('#showred').hide();
        $('#showblue').show();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').hide();
    } else {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').show();
    }
});

$(g).click(function(){
    if ($(g).is(':not(:checked)')) {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').show();
        $('#showpurple').hide();
        $('#default').hide();
    } else {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').show();
    }
});

$(p).click(function(){
    if ($(r).is(':not(:checked)') && $(b).is(':not(:checked)')) {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').show();
        $('#default').hide();
    } else {
        $('#showred').hide();
        $('#showblue').hide();
        $('#showgreen').hide();
        $('#showpurple').hide();
        $('#default').show();
    }
});        
});

http://jsfiddle.net/robert316/tu0o1z0s/13/

如果能帮助我正常工作,我将不胜感激,我希望发生的事情是:

我还想修复当用户取消选中一个框时它恢复到默认 div 显示的行为,理想情况下,如果没有选择任何框,它应该显示默认 div,并始终根据复选框的组合显示 div。

非常感谢您对此的任何帮助。

与其为每种颜色创建颜色 div,不如使用单个 color-div 并仅更改其 css 属性/类?这将消除在进行 checkbox 选择时对无关的显示隐藏/if-else 逻辑的需要。

此片段说明了如何 "return a div based on any combination of checks" - 它依赖于 css 来处理目标 div 的属性设置,但您可以在 jQuery 还有。

示例:

$(document).ready(function() {

  // checkboxes with name 'color', 'color-div', and reset button
  var colors = $("input[name='color']");
  var colorDiv = $("#color-div");
  var reset = $("#reset");



  // bind to 'colors' change event:
  colors.change(function() {

    // empty array to hold the color ids
    var idArr = [];

    // get the checked colors
    var checked = $("input[name='color']:checked");

    // loop and build array
    checked.each(function() {
      idArr.push($(this).prop("id"));
    });

    // function below   
    toggleColors(idArr, colorDiv);

  });



  // reset to defaults
  $("#reset").click(function() {

    // function below
    setDefault(colorDiv);

    // back to hidden
    colorDiv.hide();

    // uncheck the check boxes
    $("input[name='color']:checked").removeAttr("checked");
  });

});



/// function to add color css classes based on checkbox id array
function toggleColors(arr, elem) {

  var arrLen = arr.length;

  // set default if array is empty
  if (arrLen < 1) {
    setDefault(elem);
    return;
  };

  // remove classes, add classes
  elem.removeClass();
  for (i = 0; i < arrLen; i++) {
    elem.addClass(arr[i]);
  }

  // unhide
  elem.show();

}


/// set the color div to "default"
function setDefault(elem) {
  elem.removeClass();
  elem.addClass("default");
}
/* 

  using css to handle color and content change! 
  this will prevent you from having to write complicated "if-else"
  jQuery blocks.

*/

#color-div {
  height: 100px;
  width: 100px;
  border: solid 2px #d3d3d3;
  margin-bottom: 20px;
}
.default,
.default:after {
  background-color: #fff;
  content: "Please select a color";
}
.yellow,
.yellow:after {
  background-color: yellow;
  content: "I am Yellow!";
}
.red,
.red:after {
  background-color: red;
  content: "I am Red!";
}
.blue,
.blue:after {
  background-color: blue;
  content: "I am Blue!";
}
.yellow.blue,
.yellow.blue:after {
  background-color: green;
  content: "I am Green!";
}
.yellow.red,
.yellow.red:after {
  background-color: orange;
  content: "I am Orange!";
}
.blue.red,
.blue.red:after {
  background-color: purple;
  content: "I am Purple!";
}
.blue.red.yellow,
.blue.red.yellow:after {
  background-color: brown;
  content: "I am Brown :(";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="checkboxes">
  <input type="checkbox" id="red" name="color" />
  <label>Red</label>
  <input type="checkbox" id="blue" name="color" />
  <label>Blue</label>
  <input type="checkbox" id="yellow" name="color" />
  <label>Yellow</label>
</div>

<br />
<br />
<div id="color-div" style="display:none;"></div>
<button id="reset">Reset</button>

如果 css 类 不是您的包,您基本上可以通过构建等效的 javascript 对象来处理相同的 "toggling"。

[编辑 - 为每个复选框使用 Div]

由于您可以控制复选框的属性,因此您应该使用这些属性之一来绑定到您的查询正在加载的元素。您还应该尽量避免对多个元素使用 id。例如,如果你有这个:

<!-- Checkbox -->
<input type="checkbox" id="burgers" name="color" />

<!-- Loaded/hidden content div-->
<div id="burgerDiv" style="display:none;"></div>

我建议在您的复选框中添加 data-*value 属性,该属性与隐藏 div 的 id 相关联。但是,我不确定数据属性 supported in all browsers 有多好。示例:

<!-- Checkbox -->
<input type="checkbox" id="burgers" name="color" value="burgersDiv" data-ref="burgersDiv" />

... 那么 hide/show 就很容易 div:

fiddle

万一有人发现这个问题,这里是我用来显示多个复选框选择的单个 div 的最终代码:

代码段:

$(document).ready(function () {

    // select checkboxes by name
    var packages = $("input[name='cc']"); 
    // set main div id  
    var packageDiv = $("#listings"); 

    // bind to change event
    packages.change(function () {
        
        // empty array
        var idArr = [];
        // get the checked values
        var checked = $("input[name='cc']:checked");
        // loop and build array
        checked.each(function () {
            idArr.push($(this).prop("id"));
        });
        
        // remove whitespace from multiple checkboxes array
        var trimArray = idArr.join("");
        
        toggleShowHide(trimArray, packageDiv);

    });
    
});

function toggleShowHide(arr, elem) {
    
    var arrLen = arr.length;
    
    // clear last selection when unchecking boxes
    $(".hide-me").hide();
    
    // set default if array is empty
    if (arrLen < 1 ){
        setDefault(elem);
    }
    
    // run the show hide based on array of selection
    
    for(i = 0; i < arrLen; i++) {
        // set the name for the selected div
        var temp = "#" + arr + "_div_id";
        
        $(temp).show();
        $("#default").hide();
         
    } 
    
    // unhide
    elem.show();
    
}

function setDefault(elem){
    $("#default").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<!-- Checkbox -->
<input type="checkbox" id="i" name="cc" value="i_div_id" data-ref="i_div_id" />
<label>I</label>
<input type="checkbox" id="c" name="cc" value="c_div_id" data-ref="c_div_id" />
<label>C</label>
<input type="checkbox" id="p" name="cc" value="p_div_id" data-ref="p_div_id" />
<label>P</label>
        
<br />
<br />
<br />
<br />
<!-- Loaded/hidden content div-->
<div id="listings">
<div class="hide-me" id="default"><strong>This is default copy on page</strong></div>
<div class="hide-me" id="i_div_id" style="display:none;">You ordered: <strong>I Package</strong></div>
<div class="hide-me" id="c_div_id" style="display:none;">You ordered: <strong>C Package</strong></div>
<div class="hide-me" id="p_div_id" style="display:none;">You ordered: <strong>P Package</strong></div>
<div class="hide-me" id="ic_div_id" style="display:none;">You ordered: <strong>I-C Package</strong></div>
<div class="hide-me" id="ip_div_id" style="display:none;">You ordered: <strong>I-P Package</strong></div>
<div class="hide-me" id="cp_div_id" style="display:none;">You ordered: <strong>C-P Package</strong></div>
<div class="hide-me" id="icp_div_id" style="display:none;">You ordered: <strong>I-C-P Package</strong></div>
</div>