我该如何优化这段代码?

时间:2012-02-08 21:06:11

标签: javascript html

其他stackoverflow成员@mrtsherman帮我把这个小脚本放在一起,根据一些表单字段的输入生成一个句子。我改变了一点以适应我的网站,并想知道是否有一种优化代码的方法? (尤其是“案例”部分)

http://jsfiddle.net/pktMJ/3/

谢谢!

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

我不知道这是否是一个优化,但它删除了switch语句。

var verbMap =
{
    'Freshman':'studying',
    'Sophomore':'studying',
    'Junior':'studying',
    'Senior':'studying',
    'Masters Student':'studying',
    'Phd Candidate':'studying',
    'Masters Degree Holder':'having studied',
    'Phd Degree Holder':'having studied',
    'TA':'teaching',
    'Professor':'teaching',
    'Middle School Teacher':'teaching',
    'High School Teacher':'teaching'
};

document.getElementById('description').onchange = function()
    {

    document.getElementById('a').innerHTML = this.value;

    var verb = verbMap[this.value];

    document.getElementById('d').innerHTML = verb;
};