我可以用数组或循环缩小此代码吗?

时间:2012-01-08 01:04:38

标签: javascript

原谅我,我希望这个问题不太明显,我是一个javascript noob。

我有javascript代码从xml表中获取数字并在html页面上的td元素中显示它们。它可以工作,但我认为它可以压缩成数组或循环以提高效率。

有没有更好的方法来编写此代码?

window.onload=function displayPrices()
{
twentyFourK=(x[i].getElementsByTagName("twentyFourK")[0].childNodes[0].nodeValue);
document.getElementById("twentyFourK").innerHTML=toCurrency(twentyFourK);

oneOzGold=(x[i].getElementsByTagName("oneOzGold")[0].childNodes[0].nodeValue);
document.getElementById("oneOzGold").innerHTML=toCurrency(oneOzGold);

fiveOzGold=(x[i].getElementsByTagName("fiveOzGold")[0].childNodes[0].nodeValue);
document.getElementById("fiveOzGold").innerHTML=toCurrency(fiveOzGold);

tenOzGold=(x[i].getElementsByTagName("tenOzGold")[0].childNodes[0].nodeValue);
document.getElementById("tenOzGold").innerHTML=toCurrency(tenOzGold);

oneKiloGold=(x[i].getElementsByTagName("oneKiloGold")[0].childNodes[0].nodeValue);
document.getElementById("oneKiloGold").innerHTML=toCurrency(oneKiloGold);

//etc.
}

3 个答案:

答案 0 :(得分:3)

是的,功能可以让您更轻松:

window.onload = function() {
    function loadCurrency(name) {
        document.getElementById(name).innerHTML = toCurrency(x[i].getElementsByTagName(name)[0].firstChild.nodeValue);
    }

    loadCurrency('twentyFourK');
    loadCurrency('oneOzGold');
    loadCurrency('fiveOzGold');
    loadCurrency('tenOzGold');
    loadCurrency('oneKiloGold');
};

此外,如果您要加载许多项目:

window.onload = function() {
    function loadCurrency(name) {
        document.getElementById(name).innerHTML = toCurrency(x[i].getElementsByTagName(name)[0].firstChild.nodeValue);
    }

    var items = ['twentyFourK', 'oneOzGold', 'fiveOzGold', 'tenOzGold', 'oneKiloGold'];
    items.forEach(loadCurrency);
};

这需要Array.forEach,这只在ECMAScript 5中可用,所以这是一个后备:

Array.prototype.forEach = function(action, thisArg) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(i in this) {
            action.call(thisArg, this[i], i, this);
        }
    }
};

答案 1 :(得分:1)

我会将货币设置放入自己的方法中。这将在视觉上更清晰,并且还将允许将来实施变更:

window.onload = function displayPrices() {

    SetCurrency("twentyFourK");
    SetCurrency("oneOzGold");

    //etc.
}
function SetCurrency(name) {
    var elements = x[i].getElementsByTagName(name);
    if ((elements != null) && (elements.length != 0)) {
        elements[0].innerHTML = toCurrency(elements[0].childNodes[0].nodeValue);
    }
}

答案 2 :(得分:0)

你可以用参数中的元素列表创建一个函数,你只需创建一个遍历元素列表的循环(twentyFourK,oneKiloGold等)

相关问题