简体   繁体   中英

How can I write this JS code more simple, smarter?

I need shorter, smarter code becuase there is a lot of these shapes with different IDs.

const shape1 = document.getElementById('shape1');
const shape2 = document.getElementById('shape2');
const shape3 = document.getElementById('shape3');
const shape4 = document.getElementById('shape4');
const shape5 = document.getElementById('shape5');

shape1.addEventListener('click', function handleClick() {
    shape1.style.color = color
});
shape2.addEventListener('click', function handleClick() {
    shape2.style.color = color
});
shape3.addEventListener('click', function handleClick() {
    shape3.style.color = color
});
shape4.addEventListener('click', function handleClick() {
    shape4.style.color = color
});
shape5.addEventListener('click', function handleClick() {
    shape5.style.color = color
});

You can use one function with data-attribute like:

 const shapes = document.querySelectorAll('[data-shape]'); shapes.forEach(el => { el.addEventListener('click', (e) => { e.target.style.color = e.target.dataset.shape; }); });
 <div data-shape='red'>click me</div> <div data-shape='blue'>click me</div> <div data-shape='green'>click me</div>

Reference:

You can get all elements and then loop for them

like this:

// get elements by ID that STARTS WITH shape
const shapes  = document.querySelectorAll(`[id^="shape"]`);

shapes.forEach(shape=> {
  shape.addEventListener('click', () => {
    shape.style.color = color;
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM