使用一个函数而不是多个函数

Using one funnction instead of many functions

本文关键字:函数 一个      更新时间:2023-09-26

我有很多图像正在单独更新下拉选择框。我一直在使用以下内容:(在每个图像的单独函数中更改replaceContent(数字)和不同的selectIndex=(数字))。

function replaceContent9() {
     document.getElementById("ecwid-productoption-8840317-Backgrounds")
             .selectedIndex = 0 ; } 

我这样调用函数:

javascript:replaceContent9

我该如何使用数组来实现这一点,这样我可能只有一个函数用于所有图像。到目前为止,还不太擅长计算数组。也许有人可以为我指明正确的方向,或者建议一个代码来尝试。

我会使用一个散列/查找对象:

var replaceContent = (function() {
    var info = {
        0:   'ecwid-productoption-8840317-Backgrounds',
        1:   'foobar-product',
        9:   'whhooott rage'
    };
    return function( which ) {
        document.getElementById( info[ which ] ).selectedIndex = 0 ;
    };
}());

这个对象在其当前形式中看起来很像一个javascript数组,因为有索引的键名,但为了更通用,您应该这样做。

现在你可以像一样调用这个函数

replaceContent( 9 );