Jquery 优化IF语句的更好方法
有没有更好的方法来优化jQuery中的以下IF语句 我已经编辑了以下代码好几次了,如果我能在一个好的数组中插入必要的值或其他东西,那就太好了Jquery 优化IF语句的更好方法,jquery,Jquery,有没有更好的方法来优化jQuery中的以下IF语句 我已经编辑了以下代码好几次了,如果我能在一个好的数组中插入必要的值或其他东西,那就太好了 $("#pmselect").change(function () { if ($("#pmselect option:selected").attr("class") == "null") { $('.avatar').hide(); $('.pmpass').hide();
$("#pmselect").change(function () {
if ($("#pmselect option:selected").attr("class") == "null") {
$('.avatar').hide();
$('.pmpass').hide();
$('.pmlogin').hide();
$('#nullavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "pm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#pmavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "as") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#asavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "pn") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#pnavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "jm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#jmavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "mh") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#mhavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "rh") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#rhavatar').show();
}
if ($("#rmselect option:selected").attr("id") == "rm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#rmavatar').show();
}
});
您可以使用switch/case,这样您就可以在多个案例中整合一些可以完成的事情
switch( $("#pmselect option:selected").attr("id") ){
case 'pm':
//do stuff
break;
case 'xyz':
case 'rh':
//do stuff for xyz and rh
case 'mh':
// do stuff for mh only
break;
}
试试这个:
$("#pmselect").change(function () {
$('.avatar').hide();
if ($("#pmselect option:selected").attr("class") == "null") {
$('.pmpass, .pmlogin').hide();
$('#nullavatar').show();
} else {
var id = $("#pmselect option:selected").attr("id");
$('.pmpass, .pmlogin').show();
$('.pmlogin').show();
$('#' + id + 'avatar').show();
}
});
假设最后一个if表达式中的$(“#rmselect option:selected”)
是一个打字错误(归功于eagle eyed@RaymondChen),我想您会发现代码简化为:
$("#pmselect").change(function () {
var opt = this[this.selectedIndex],
isNull = $(opt).hasClass('null'),
id = isNull ? 'null' : opt.id;
$('.avatar').hide();
$('.pmpass, .pmlogin')[isNull ? 'hide' : 'show']();
$('#' + id + 'avatar').show();
});
如果在视线内,则没有:)
如果$(“#rmselect option:selected”)
不是打字错误,则需要单独处理#rmselect条件。switch/case语句??除了第一个If
,您是根据元素的id
进行选择的。使用开关
进行清洁。还考虑如果所有的显示/隐藏逻辑都可以移动到单独的函数,以便你可以将它与你的交换机分离/如果已经编写和工作的StaseTimeScript代码> @ RaymondChen同意,CoDeEvIEW是一个更好的位置,这个问题代码就更合适了(但是)请参阅下面的答案。“#pmselect option:selected”).attr('id'){
:)除了在原始代码中,最后一个if
测试#rmselect
而不是#pmselect
。