如果语句更有效,我怎么能写这个呢?

use*_*221 2 javascript if-statement

我有一个带有一些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');" />
Run Code Online (Sandbox Code Playgroud)

 

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';
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 5

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

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'
Run Code Online (Sandbox Code Playgroud)