首页 > 解决方案 > 如何优化代码,让我不必每次都写一个新数字?

问题描述

我有这样的js代码:

 lightGallery($("#web1")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: false,
    }
});
lightGallery($("#web2")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: true,
    }
});
lightGallery($("#web3")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: true,
    }
});

如何优化代码,让我不必每次都写一个新数字?

标签: javascriptjqueryoptimizationlightgallery

解决方案


您可以使用for循环:

let lowerLimit = 1;
let upperLimit = 3;

for (let i = lowerLimit; i <= uppperLimit; i++) {
    lightGallery($("#web" + i)[0], {
        selector: 'this',
        mobileSettings: {
            controls: false,
            showCloseIcon: true,
            download: false,
        }
    });
}

推荐阅读