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

Time:10-08

I have js code like this:

 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,
    }
});

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

CodePudding user response:

You can use a for loop:

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,
        }
    });
}

CodePudding user response:

Consider the following.

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

This will go over each one that has an ID that starts web and apply the same code.

  • Related