gpt4 book ai didi

javascript - 我怎样才能更有效地编写这个 else if 语句?

转载 作者:行者123 更新时间:2023-12-03 09:54:10 27 4
gpt4 key购买 nike

我有一个带有一些 css 自定义按钮的页面,我希望当用户单击页面上的其他地方时,所选按钮保持突出显示。我可以得到我想要的东西写一个 if/else 语句来在选择按钮时分配一个类,如果没有选择按钮则分配一个不同的类但它很啰嗦,我怎样才能更有效地编写它?

<input class="btn" id="moveIt_overall2" type="button" value="Overall" onclick="changeImpactState('impact_overall');"/>
<input class="btn" id="moveIt_customer" type="button" value="Customer" onclick="changeImpactState('impact_customer');" />
<input class="btn" id="moveIt_staff" type="button" value="Staff" onclick="changeImpactState('impact_staff');" />
<input class="btn" id="moveIt_strategic" type="button" value="Strategic" onclick="changeImpactState('impact_strategic');" />

var moveItOverall = document.getElementById('moveIt_overall2');
var moveItCustomer = document.getElementById('moveIt_customer');
var moveItStaff = document.getElementById('moveIt_staff');
var moveItStrategic = document.getElementById('moveIt_strategic');

if(currentImpactState == 'impact_overall'){
moveItOverall.className = 'btn-on';
moveItCustomer.className = 'btn';
moveItStaff.className = 'btn';
moveItStrategic.className = 'btn';
}else if(currentImpactState == 'impact_customer'){
moveItOverall.className = 'btn';
moveItCustomer.className = 'btn-on';
moveItStaff.className = 'btn';
moveItStrategic.className = 'btn';
}else if(currentImpactState == 'impact_staff'){
moveItOverall.className = 'btn';
moveItCustomer.className = 'btn';
moveItStaff.className = 'btn-on';
moveItStrategic.className = 'btn';
}else if(currentImpactState == 'impact_strategic'){
moveItOverall.className = 'btn';
moveItCustomer.className = 'btn';
moveItStaff.className = 'btn';
moveItStrategic.className = 'btn-on';
}

最佳答案

您实际上是将 currentImpactState 映射到 DOM 中的 ID。您可以显式制作此 map ,然后使用它来查找要更改的对象。

const buttons = {
impact_overall: 'moveIt_overall2',
impact_customer: 'moveIt_customer',
impact_staff: 'moveIt_staff',
impact_strategic: 'moveIt_strategic'
}

// change everything
Object.values(buttons).forEach(id => document.getElementById(id).className = 'btn' )
// change the item currentImpactState indicates
document.getElementById(buttons[currentImpactState]).className = 'btn-on'

关于javascript - 我怎样才能更有效地编写这个 else if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51585741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com