【问题标题】:How do I optimize the code so that I don't have to write a new number every time?如何优化代码,让我不必每次都写一个新数字?
【发布时间】:2021-11-27 22:04:03
【问题描述】:

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

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

【问题讨论】:

  • 欢迎来到 Stack Overflow。您可能希望使用.each() 来迭代每个项目。那么这就是正确选择器的问题。

标签: javascript jquery optimization lightgallery


【解决方案1】:

考虑以下内容。

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

这将遍历 ID 以 web 开头的每个 ID,并应用相同的代码。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-21
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多