首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有效隐藏和显示类

有效隐藏和显示类
EN

Stack Overflow用户
提问于 2016-11-25 08:27:39
回答 1查看 74关注 0票数 1

我想知道是否可以将下面的代码简化/规范化为更有效的代码。代码的工作原理是应该的,但我认为它可能更小。当选择无线电选项时,它基本隐藏并显示类。

代码语言:javascript
运行
复制
$("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");
    }
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-25 09:08:44

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

代码语言:javascript
运行
复制
var $content = $("[data-content]");

$("input[type='radio']").on("change", function() {
  $content.hide(260).filter("[data-content='"+ this.dataset.show +"']").show(260);
});
代码语言:javascript
运行
复制
[data-content]{display:none;} /* hide initially */
代码语言:javascript
运行
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40800565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档