jQuery:根据任意数量的复选框隐藏/显示div

时间:2018-01-21 22:45:40

标签: javascript jquery html

我有following code

<div class="row">
    <div class="col-xs-4">
            <label class="checkbox-inline"><input type="checkbox" value="draft">Borrador</label>
    </div>
    <div class="col-xs-4">
            <label class="checkbox-inline"><input type="checkbox" value="cancel">Cancelado</label>
    </div>
        <div class="col-xs-4">
            <label class="checkbox-inline"><input type="checkbox" value="waiting" checked>Esperando</label>
    </div>
</div>
<div class="row">
    <div class="col-xs-4">
        <label class="checkbox-inline"><input type="checkbox" value="partially_available" checked>Parc. Disp.</label>
    </div>
        <div class="col-xs-4">
            <label class="checkbox-inline"><input type="checkbox" value="confirmed" checked>Confirmado</label>
    </div>
        <div class="col-xs-4">
            <label class="checkbox-inline"><input type="checkbox" value="assigned" checked>Asignado</label>
    </div>
</div>
<div class="row">
    <div class="col-xs-4">
        <label class="checkbox-inline"><input type="checkbox" value="done">Hecho</label>
    </div>
</div>


<div state="draft">Div1</div>
<div state="done">Div2</div>
<div state="assigned">Div3</div>
<div state="assigned">Div4</div>
<div state="done">Div5</div>

其中包含一组复选框,每个复选框都有一个特定的初始状态(已选中/未选中)和一个值。如果需要,他们可以指定一个名称。

有一个<div>的任意数字,其中包含一个名为state的属性(与其中一个checbox相匹配)。

  • jQuery中应该使用什么来使用户每次与相应<div>对应的复选框进行交互时隐藏或显示?
  • jQuery中应该使用什么来确保根据checbox状态运行intiial round以正确隐藏/显示<div>

谢谢!,

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

// Iterates over each checkbox on window load
$(window).on('load',()=>{
  $('input[type="checkbox"]').each(toggleDivs);
});

// binds an onchange handler to each checkbox
$('input[type="checkbox"]').on('change',toggleDivs);

function toggleDivs(){
  // if its checked, show the div with the state equivelant to the checkbox's value
  if($(this).is(':checked')) $('div[state="' + $(this).val() + '"]').show();
  // otherwise hide it
  else  $('div[state="' + $(this).val() + '"]').hide();
}
  

注意:此代码未经测试,可能需要进行一些校对