简体   繁体   中英

How can I get multiple elements to work with JavaScript?

So when I click the checkbox, the background colour changes. I want this function to work for all checkboxes, but it is currently only working for the first one.

 function obtained() { var obt = document.getElementsByClassName("obtained")[0]; var col = document.getElementsByClassName("entry")[0]; if (obt.checked == true) { col.style.backgroundColor = "#2ab320"; } else { col.style.backgroundColor = "#d3d5db"; } }
 <div class="entry"> <img class="class-name" src="image1.png"> <b>title1</b><br>content1 <input type="checkbox" class="obtained" onclick="obtained()" name="obtained" > </div><hr> <div class="entry"> <img class="class-name" src="image2.png"> <b>title2</b><br>content2 <input type="checkbox" class="obtained" onclick="obtained()" name="obtained" /> </div><hr> <div class="entry"> <img class="class-name" src="image3.png"> <b>title3</b><br>content3 <input type="checkbox" class="obtained" onclick="obtained()" name="obtained" /> </div><hr>

In cases like this one you should declare a helper function:

function makeTogglable(element) {
  const obt = element.querySelector(".obtained");
  obt.addEventListener("click", () => {
    if(obt.checked == true) {
      element.style.backgroundColor = "#2ab320";
    } else {
      element.style.backgroundColor = "#d3d5db";
    }
  });
}

Then you can apply it your HTML elements, for example:

document.querySelectorAll('.entry').forEach(e => makeTogglable(e));

Edit: forgot about listeners

You could pass an instance of the checkbox to the function like so:

 function obtained(element) { var col = element.parentElement; if (element.checked == true) { col.style.backgroundColor = "#2ab320"; } else { col.style.backgroundColor = "#d3d5db"; } }
 <div class="entry"> <img class="class-name" src="image1.png"> <b>title1</b><br>content1 <input type="checkbox" class="obtained" onclick="obtained(this)" name="obtained" > </div><hr> <div class="entry"> <img class="class-name" src="image2.png"> <b>title2</b><br>content2 <input type="checkbox" class="obtained" onclick="obtained(this)" name="obtained" /> </div><hr> <div class="entry"> <img class="class-name" src="image3.png"> <b>title3</b><br>content3 <input type="checkbox" class="obtained" onclick="obtained(this)" name="obtained" /> </div><hr>

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