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

How do I optimize the code so that I don't have to write a new number every time?

我有这样的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,
    }
});

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

您可以使用 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,
        }
    });
}

考虑以下因素。

$("[id^='web']").each(function(i, el){
  lightGallery($(el)[0], {
    selector: 'this',
    mobileSettings: {
      controls: false,
      showCloseIcon: true,
      download: false,
    }
  });
});

这将检查 ID 以 web 开头的每一个并应用相同的代码。