【问题标题】:Reduce switch statement with variable?减少带有变量的switch语句?
【发布时间】:2018-11-18 16:45:33
【问题描述】:

我有一个 switch 语句,根据按钮的属性,显示具有此属性的 div,并隐藏不具有此属性的 div。除了我有多个属性的代码的多行。但最终代码始终是一样的,只是属性名称发生了变化。有没有办法将属性的名称也设置为变量并且只有一行代码(然后最有可能删除开关)?

这是我到目前为止的代码(只有几行,以后还会有很多):

jQuery :

$(".button").on("click", function(){
  var lequel = $(this).attr("data-auteur");

  switch(lequel) {
    case "descartes" :
      $(".idee[data-auteur='descartes']").show();
      $(".idee[data-auteur!='descartes']").hide();
      break;

    case "hobbes" :
      $(".idee[data-auteur='hobbes']").show();
      $(".idee[data-auteur!='hobbes']").hide();
      break;

    case "marx" :
      $(".idee[data-auteur='marx']").show();
      $(".idee[data-auteur!='marx']").hide();
      break;

    case "platon" :
      $(".idee[data-auteur='platon']").show();
      $(".idee[data-auteur!='platon']").hide();
      break;
  }
})

如果您想要 html,请告诉我,但我认为这个想法很清楚。有特定属性的按钮和具有相同特定属性的div下

【问题讨论】:

  • 将变量附加到选择器中:$('.idee[auteur="' + lequel + '"]').show();。另请注意,auteur 不是有效属性。如果您想将自定义元数据添加到元素,我建议使用 data 属性;以data-auteur="marx" 为例
  • 感谢您的回复,所以如果我将变量附加到选择器中,这意味着我删除了整个 switch 语句并将其替换为您建议的行?还有感谢关于属性的建议,我会改的!
  • 没错。我在下面的答案中添加了一个示例以使其更清楚。
  • 该死的。使用一些 mvvm 框架
  • @RegisPortalez 抱歉,但我不知道那是什么。我正在尝试用我对 jquery 的一点了解来创建这个项目。我知道这并不完美,但我正在尽力而为

标签: jquery attributes switch-statement


【解决方案1】:

最小的变化是使用字符串连接:

$(".button").on("click", function(){
  var auteur = $(this).attr("auteur");

  $(".idee[auteur='" + auteur + "']").show();
  $(".idee[auteur!='" + auteur + "']").hide();
})

您也可以避免查询 DOM 两次,尽管这样也可以:

$(".button").on("click", function(){
  var auteur = $(this).attr("auteur");

  $(".idee")
    .filter("[auteur='" + auteur + "']").show().end()
    .filter("[auteur!='" + auteur + "']").hide();
})

【讨论】:

  • 感谢您的建议,我会避免查询 DOM 两次!
  • @MaëlleJumel - :-) 这没什么大不了的。编码愉快!
【解决方案2】:

首先注意auteur 不是一个有效的属性。如果您想将自定义元数据添加到元素,我建议使用 data 属性;以data-auteur="marx" 为例。

关于您的问题,您可以通过将变量附加到选择器中来避免切换并缩短逻辑:

$(".button").on("click", function() {
  var lequel = $(this).data("auteur");
  $('.idee[data-auteur="' + lequel + '"]').show();
  $('.idee[data-auteur!="' + lequel + '"]').hide();
})
.idee {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" data-auteur="descartes">Descartes</button>
<button class="button" data-auteur="hobbes">Hobbes</button>
<button class="button" data-auteur="marx">Marx</button>
<button class="button" data-auteur="platon">Platon</button>

<div class="idee" data-auteur="descartes">
  Descartes content...
</div>
<div class="idee" data-auteur="hobbes">
  Hobbes content...
</div>
<div class="idee" data-auteur="marx">
  Marx content...
</div>
<div class="idee" data-auteur="platon">
  Platon content...
</div>

【讨论】:

  • 非常感谢!现在很清楚了。而且容易很多。祝你有美好的一天
  • 没问题,很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
相关资源
最近更新 更多