我目前正在进行的项目非常简单,并使用oCanvas绘制7段数字时钟(总共有6组段代表HH:MM:SS)。我的代码工作正常,但元素名称是硬编码的,我想优化我的脚本,以便最终得到一个函数,该函数采用段“set”的名称(例如,秒的最右边的数字)列)以及每个段(1到7)的TRUE / FALSE值,然后根据是否应该打开来更改oCanvas元素的颜色。
我的功能目前看起来像这样,我刚刚包含了秒列最右边数字的代码 - 实际上在if()测试中有六个条件,而不仅仅是显示的那个:
function display_segments(type,seg_01,seg_02,seg_03,seg_04,seg_05,seg_06,seg_07)
{
var segment_on = "#FF0000";
var segment_off = "#333333";
var seg_val_01, seg_val_02, seg_val_03, seg_val_04, seg_val_05, seg_val_06, seg_val_07;
(seg_01) ? seg_val_01 = segment_on : seg_val_01 = segment_off;
(seg_02) ? seg_val_02 = segment_on : seg_val_02 = segment_off;
(seg_03) ? seg_val_03 = segment_on : seg_val_03 = segment_off;
(seg_04) ? seg_val_04 = segment_on : seg_val_04 = segment_off;
(seg_05) ? seg_val_05 = segment_on : seg_val_05 = segment_off;
(seg_06) ? seg_val_06 = segment_on : seg_val_06 = segment_off;
(seg_07) ? seg_val_07 = segment_on : seg_val_07 = segment_off;
// This section needs optimising
if (type == 'seconds_right') {
segment_01_seconds_right.stroke = "5px " + seg_val_01;
segment_02_seconds_right.stroke = "5px " + seg_val_02;
segment_03_seconds_right.stroke = "5px " + seg_val_03;
segment_04_seconds_right.stroke = "5px " + seg_val_04;
segment_05_seconds_right.stroke = "5px " + seg_val_05;
segment_06_seconds_right.stroke = "5px " + seg_val_06;
segment_07_seconds_right.stroke = "5px " + seg_val_07;
} else {
// 5 else if() tests at this point
}
canvas.redraw(); // oCanvas
}
我想要做的是用for()循环替换此代码,该循环使用当前“type”变量中的值代替硬编码元素名称“segment_XX_seconds_right”,但我无法工作如何做到这一点,我不想在可能的情况下使用eval()。
提前感谢您的任何帮助或建议!