如何在没有框架的情况下缩短/改进此JavaScript?

时间:2011-12-02 23:53:50

标签: javascript

function prepareEventHandlers() {
    var sectionButton1 = document.getElementById("sectionButton1");
    var sectionButton2 = document.getElementById("sectionButton2");
    var sectionButton3 = document.getElementById("sectionButton3");
    var sectionButton4 = document.getElementById("sectionButton4");
    var sectionButton5 = document.getElementById("sectionButton5");

    var enabled1 = true;
    var enabled2 = false;
    var enabled3 = false;
    var enabled4 = false;
    var enabled5 = false;


    function checkEnabled() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonEnabled");
        }

    }

    checkEnabled();
    sectionButton1.onmouseover = function() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton1.onmouseout = function() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton2.onmouseover = function() {
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton2.onmouseout = function() {
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton3.onmouseover = function() {
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton3.onmouseout = function() {
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton4.onmouseover = function() {
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton4.onmouseout = function() {
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton5.onmouseover = function() {
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton5.onmouseout = function() {
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonEnabled");
        }
    };
}


window.onload = function() {
    prepareEventHandlers();
};

4 个答案:

答案 0 :(得分:3)

每当你发现自己编写变量名称如“foo1”,“foo2”等等,并且它们或多或少都做同样的事情时,你真的需要停止,备份和声明一个数组。

function prepareEventHandlers() {
    var sectionButtons = [];
    for (var i = 1; i <= 5; ++i)
      sectionButtons[i] = document.getElementById('sectionButton' + i);

    var enabled = [ true, false, false, false, false ];

    function checkEnabled() {
        for (var i = 1; i <= 5; ++i)
          if (enabled[i]) sectionButtons[i].className = 'sectionButtonEnabled';
    }

    checkEnabled();

    for (i = 1; i <= 5; ++i) {
      sectionButton[i].onmouseover = function(i) {
        return function() {
          if (enabled[i]) sectionButton[i].className = 'sectionButtonOver');
        }
      }(i);
      sectionButton[i].onmouseout = function(i) {
        return function() {
          if (enabled[i]) sectionButton[i].className = 'sectionButtonEnabled';
      }(i);
    }
}


window.onload = function() {
    prepareEventHandlers();
};

现在,另外两件事:

  1. 不要使用“setAttribute()”设置“class”属性。相反,操纵DOM元素的“className”属性。
  2. 不是直接将类设置为这些字符串,而是构建自己的“addClass()”和“removeClass()”函数。请记住,该类可以是类名的列表,用空格分隔。这些功能看起来像这样:

    function addClass(elem, c) {
      elem.className += ' ' + c;
    }
    
    function removeClass(elem, c) {
      elem.className = elem.className.replace(new RegExp('\\b' + c + '\\b', 'g'), ''));
    }
    

答案 1 :(得分:2)

修改

我同意很多其他答案谈论将数据存储在数组中,但我会使用一个对象数组来代替并行数组:

var i, buttonData = [];
for(i = 1; i <= 5; i++)
   buttonData.push({ "enabled" : false, 
                     "button": document.getElementById("sectionButton" + i) });
buttonData[0].enabled = true;

然后:

for (i = 0; i < buttonData.length; i++) {
     setClassIfEnabled(buttonData[i].enabled, buttonData[i].button)
}

或者如果你想保持简单,下面的原始答案仍然会删除原始版本中的大量代码:


使用辅助方法重构代码

function setClassIfEnabled(enabled, button){
    if (enabled) {
          button.setAttribute("class", "sectionButtonEnabled");
    }
}

然后

function checkEnabled() {
     setClassIfEnabled(enabled1, sectionButton1);
     setClassIfEnabled(enabled2, sectionButton2);
     setClassIfEnabled(enabled3, sectionButton3);
     setClassIfEnabled(enabled4, sectionButton4);
     setClassIfEnabled(enabled5, sectionButton5);
}

另外

function setMouseOverIfEnabled(enabled, button) {
    button.onmouseover = function() {
        if (enabled) {
            button.setAttribute("class", "sectionButtonEnabled");
        }
    };
}

setMouseOverIfEnabled(enabled1, sectionButton1);
setMouseOverIfEnabled(enabled2, sectionButton2);
setMouseOverIfEnabled(enabled3, sectionButton3);
setMouseOverIfEnabled(enabled4, sectionButton4);
setMouseOverIfEnabled(enabled5, sectionButton5);

当然对mouseout

做同样的事情

此外,您可能需要考虑使用addEventListener添加活动

function setMouseOverIfEnabled(enabled, button) {
    button.addEventListener("mouseover", function() {
        if (enabled) {
            button.setAttribute("class", "sectionButtonEnabled");
        }
    });
}

答案 2 :(得分:0)

这是一个精简版。你绝对不想用不同的变量重复代码块。使用循环或创建本地函数。在这种情况下,由于您的ID是顺序的,因此循环在此处运行良好:

function prepareEventHandlers()
{
    var button;
    var enabled = [true, false, false, false, false];
    for (var i = 0; i < enabled.length; i++) {
        button = document.getElementById("sectionButton" + (i + 1));
        button.buttonEnabled = enabled[i];
        if (button.buttonEnabled) {
           button.className = "sectionButtonEnabled";
        }
        button.onmouseover = function() {
            if (this.buttonEnabled) {
                this.className = "sectionButtonOver";
            }
        }
        button.onmouseout = function() {
            if (this.buttonEnabled) {
                this.className = "sectionButtonEnabled";
            }
        }
    }
}

此代码还允许您稍后通过操作按钮的buttonEnabled属性和/或className来启用其他代码中的按钮,事件处理程序将自动执行正确的操作。

答案 3 :(得分:0)

首先:使用onmouseover和onmouseout来设置样式按钮是20世纪90年代的一些东西。你现在可以用CSS做同样的事情。

.sectionButtonEnabled       { regular styles here }
.sectionButtonEnabled:hover { mouseover styles here }

(注意,对于IE,这需要“标准模式” - 读取:有一个doctype行 - 和IE7或更高版本。)

现在,如果你真的想用旧的和破坏的方式做事......

function prepareEventHandlers() {
    var buttons = [
        "sectionButton1",
        "sectionButton2",
        "sectionButton3",
        "sectionButton4",
        "sectionButton5"
    ];
    var enabled = [ true, false, false, false, false ];

    for (var i = 0; i < buttons.length; ++i) {
        var elem = document.getElementById(buttons[i]);
        if (enabled[i]) {
            elem.className   = "sectionButtonEnabled";

            // Since you're only attaching the event handler to enabled buttons,
            // you already know that `enabled` is true. So you don't even need to
            // check, since there's no way to change your local variable.

            elem.onmouseover = function() {
                this.className="sectionButtonOver";
            };
            elem.onmouseout  = function() {
                this.className="sectionButtonEnabled";
            };
        }
    }
}

如果你不需要鼠标悬停处理程序,你可以摆脱它们,只使用上面提到的CSS。