有效隐藏&节目课

时间:2016-11-25 08:27:39

标签: javascript jquery html hide show

我想知道下面的代码是否可以更简单地简化/规范化为更高效的东西。代码工作正常,但我认为它可能更小。它在选择无线电选项时基本隐藏和显示类。

$("input[type='radio']").click(function () {    
      if ($("#type1").is(":checked")) {
    $("#showstoring").show("fast") &&
    $("#showonderhoud").hide("fast") &&
    $("#showspoed").hide("fast");
    } else if ($('#type2').is(':checked')) {
    $("#showstoring").hide("fast") &&
    $("#showonderhoud").hide("fast") &&
    $("#showspoed").show("fast");
    } else if ($('#type0').is(':checked')) {
    $("#showstoring").hide("fast") &&
    $("#showonderhoud").show("fast") &&
    $("#showspoed").hide("fast");
    } else {
    $("#showstoring").hide("fast") &&
    $("#showonderhoud").hide("fast") &&
    $("#showspoed").hide("fast");
    }
});

1 个答案:

答案 0 :(得分:1)

使用data-*属性按该数据值交叉引用按钮和元素:

var $content = $("[data-content]");

$("input[type='radio']").on("change", function() {
  $content.hide(260).filter("[data-content='"+ this.dataset.show +"']").show(260);
});
[data-content]{display:none;} /* hide initially */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" data-show="1" name="r">A
<input type="radio" data-show="2" name="r">B
<input type="radio" data-show="3" name="r">C
<input type="radio"               name="r" checked> Else?<br>

<div data-content="1">AAA</div>
<div data-content="2">BBB</div>
<div data-content="3">CCC</div>