我有一个 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下面
最佳答案
首先请注意,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>
关于jquery - 减少带有变量的 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50763750/