Javascript重构

时间:2010-02-19 15:57:37

标签: javascript refactoring

有没有更好的方法来编写此功能?我继承了一些javascript代码,如果可能的话我想让它更简洁。另外,我可能会添加更多“主题”元素,并且不想一遍又一遍地复制和粘贴。

function imageClick() {
var theme1 = document.getElementById("li-theme1");
var theme2 = document.getElementById("li-theme2");
var theme3 = document.getElementById("li-theme3");

var imgtheme1 = theme1.getElementsByTagName("img");
var imgtheme2 = theme2.getElementsByTagName("img");
var imgtheme3 = theme3.getElementsByTagName("img");

var inputtheme1 = document.getElementById("radiotheme1");
var inputtheme2 = document.getElementById("radiotheme2");
var inputtheme3 = document.getElementById("radiotheme3");

imgtheme1[0].onclick = function() {
    inputtheme1.checked = true;
    highlightChoice("li-theme1");
}
imgtheme2[0].onclick = function() {
    inputtheme2.checked = true;
    highlightChoice("li-theme2");
}
imgtheme3[0].onclick = function() {
    inputtheme3.checked = true;
    highlightChoice("li-theme3");
}
}

2 个答案:

答案 0 :(得分:4)

我已将imageClick()函数“硬编码”为您指定的函数,但您可以将其更改为“for(var i = 1; i< 4; i ++){imageClickItem(i)如果你愿意,可以输入循环。

function imageClick()
{
    imageClickItem(1);
    imageClickItem(2);
    imageClickItem(3);
}

function imageClickItem(itemNumber)
{
    var theme = document.getElementById("li-theme" + itemNumber);
    var imgtheme = theme.getElementsByTagName("img");
    var inputtheme = document.getElementById("radiotheme" + itemNumber);

    imgtheme[0].onclick = function()
    {
        inputtheme.checked = true;
        highlightChoice(theme.id);
    }
}

答案 1 :(得分:4)

function imageClick() 
{
    for (var i=1; i<4; i++)
    { 
        var theme = document.getElementById("li-theme"+i);
        var imgtheme = theme.getElementsByTagName("img");
        imgtheme[0].onclick = (function (current) 
        { 
            return function() 
            {
                document.getElementById("inputtheme"+current) = true;
                highlightChoice("li-theme"+current);
            }
        })(i);
    }
} 

如果您想在以后添加更多迭代,只需将4中的i<4增加到您想要执行的迭代次数+。