Javascript работает только для одного элемента, только для первого

У меня есть несколько элементов кнопки флажка на моей странице, всякий раз, когда кто-то нажимает на каждый из них, их цвет и текст меняются, я смог сделать это с помощью CSS, но я также хотел изменить значок в кнопке флажка, поэтому я использую javascript в моем HTML-коде, но когда я запускаю скрипт, он работает только для одного элемента, только для первого, так что это означает, что значок меняется только для первой кнопки флажка, но он не работает для всех остальных кнопок, я пытался дать все мои кнопки флажка имеют уникальный идентификатор, но у меня все еще та же проблема

Это флажок 1 и 2, если он не выбран Javascript работает только для одного элемента, только для первого

Это флажок 1 и 2 при выборе Javascript работает только для одного элемента, только для первого

Вот код, который я запускаю для этого:

 document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementById('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);
.select{
  margin: 4px;
  background-color: #06213B;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.select label {
  float: left; line-height: 4.0em;
  width: 26.0em; height: 4.0em;
}

.select label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.select label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.select label input + span{color: #fff;
    font-size: 19px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.select input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.select input:checked + span{background-color: #78E821;}

input[type = "checkbox"] + span:after{
  content: "Select all"; 
}

input[type = "checkbox"]:checked + span:after{
  content: "All selected"; 
}



.branded{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.branded label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.branded label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.branded label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.branded label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.branded input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.branded input:checked + span{background-color: #78E821;}

.branded input[type = "checkbox"] + span:after{
  content: "SELECT"; 
}

.branded input[type = "checkbox"]:checked + span:after{
  content: "SELECTED"; 
}


.lifepoints{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.lifepoints label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.lifepoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.lifepoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.lifepoints label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.lifepoints input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.lifepoints input:checked + span{background-color: #78E821;}

.lifepoints input[type = "checkbox"] + span:after{
  content: "SELECT"; 
}

.lifepoints input[type = "checkbox"]:checked + span:after{
  content: "SELECTED"; 
}


.mypoints{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.mypoints label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.mypoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.mypoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.mypoints label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.mypoints input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.mypoints input:checked + span{background-color: #78E821;}

.mypoints input[type = "checkbox"] + span:after{
  content: "SELECT"; 
}

.mypoints input[type = "checkbox"]:checked + span:after{
  content: "SELECTED"; 
}
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src = "https://kit.fontawesome.com/6e6e078929.js" crossorigin = "anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class = "select action">
   <label>
      <input type = "checkbox" value = "1" id = "checkbox"><span><i class = "fa-solid fa-circle" id = "icon"></i> &nbsp;</span>
   </label>
</div>
  
</body>
</html>



<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src = "https://kit.fontawesome.com/6e6e078929.js" crossorigin = "anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class = "branded surveys">
   <label>
      <input type = "checkbox" value = "1" id = "checkbox"><span><i class = "fa-solid fa-circle" id = "icon"></i> &nbsp;</span>
   </label>
</div>

</body>
</html>


<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src = "https://kit.fontawesome.com/6e6e078929.js" crossorigin = "anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class = "lifepoints">
   <label>
      <input type = "checkbox" value = "1" id = "checkbox"><span><i class = "fa-solid fa-circle" id = "icon"></i> &nbsp;</span>
   </label>
</div>

</body>
</html>


<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src = "https://kit.fontawesome.com/6e6e078929.js" crossorigin = "anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class = "mypoints">
   <label>
      <input type = "checkbox" value = "1" id = "checkbox"><span><i class = "fa-solid fa-circle" id = "icon"></i> &nbsp;</span>
   </label>
</div>
  
<script>
  document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementById('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);
</script>

</body>
</html>

Если вам нужно более организованное представление и чтобы увидеть, как взаимодействует код, взгляните на него здесь: https://codepen.io/edengandhi/pen/BaJoJYY

Вы не можете повторно использовать идентификатор. Идентификаторы ДОЛЖНЫ быть уникальными. Используйте класс и делегируйте

mplungjan 17.03.2022 14:39
document.getElementById('checkbox') нацелен только на первый элемент с этим id. Не следует возобновлять id. Используйте другой селектор, например document.querySelectorAll('input[type=checkbox]').
Lain 17.03.2022 14:39
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
58
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы не можете повторно использовать идентификатор. Идентификаторы ДОЛЖНЫ быть уникальными. Используйте класс и делегируйте

И у вас может быть только ОДИН набор тегов html, head и body.

Используйте класс и делегируйте из контейнера

Я также перехожу к i из ближайшего ("div"), но вместо этого мог бы использовать nextElementSibling

наконец, я добавил функциональность selectAll, которая была нетривиальной - диапазон раздражает. Если вы удалите диапазон из i, то все .closest('div').querySelector('i') можно изменить на .nextElementSibling

Примечание. Я публикую полный HTML-документ, чтобы показать вам структуру Таблица стилей и скрипт должны быть внешними

.select {
  margin: 4px;
  background-color: #06213B;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.select label {
  float: left;
  line-height: 4.0em;
  width: 26.0em;
  height: 4.0em;
}

.select label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.select label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.select label input+span {
  color: #fff;
  font-size: 19px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.select input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.select input:checked+span {
  background-color: #78E821;
}

input[type = "checkbox"]+span:after {
  content: "Select all";
}

input[type = "checkbox"]:checked+span:after {
  content: "All selected";
}

.branded {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.branded label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.branded label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.branded label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.branded label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.branded input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.branded input:checked+span {
  background-color: #78E821;
}

.branded input[type = "checkbox"]+span:after {
  content: "SELECT";
}

.branded input[type = "checkbox"]:checked+span:after {
  content: "SELECTED";
}

.lifepoints {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.lifepoints label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.lifepoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.lifepoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.lifepoints label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.lifepoints input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.lifepoints input:checked+span {
  background-color: #78E821;
}

.lifepoints input[type = "checkbox"]+span:after {
  content: "SELECT";
}

.lifepoints input[type = "checkbox"]:checked+span:after {
  content: "SELECTED";
}

.mypoints {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.mypoints label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.mypoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.mypoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.mypoints label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.mypoints input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.mypoints input:checked+span {
  background-color: #78E821;
}

.mypoints input[type = "checkbox"]+span:after {
  content: "SELECT";
}

.mypoints input[type = "checkbox"]:checked+span:after {
  content: "SELECTED";
}
<!doctype html>
<html>

<head>
  <title>Test</title>
  <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.0/css/all.min.css" />
  <script>
    window.addEventListener('DOMContentLoaded', function() {
      const checks = document.querySelectorAll('.chk');
      const checkAll = document.getElementById('selectAll')
      document.addEventListener('click', function(e) {
        const tgt = e.target;
        if (tgt.matches('.chk')) {
          if (tgt.id === "selectAll") {
            tgt.closest('div').querySelector('i').classList[tgt.checked ? 'add' : 'remove']('fa-circle-check');
            checks.forEach(chk => {
              chk.checked = tgt.checked
              chk.closest('div').querySelector('i').classList[chk.checked ? 'add' : 'remove']('fa-circle-check');
            })
          } else {
            tgt.closest('div').querySelector('i').classList[tgt.checked ? 'add' : 'remove']('fa-circle-check');
            checkAll.checked = [...checks].slice(1).every(chk => chk.checked); // check all sub checkboxes are checked
            checkAll.closest('div').querySelector('i').classList[checkAll.checked ? 'add' : 'remove']('fa-circle-check');
          }
        }
      });
    });
  </script>
</head>

<body>
  <div class = "select action">
    <label>
      <input type = "checkbox" class = "chk" id = "selectAll" value = "1"><span><i class = "fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div>
  <div class = "branded surveys">
    <label>
      <input type = "checkbox" class = "chk" value = "1"><span><i class = "fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div><br clear = "all" />
  <h2>Some other place</h2><br clear = "all" />
  <div class = "lifepoints">
    <label>
      <input type = "checkbox" class = "chk" value = "1"><span><i class = "fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div><br clear = "all" />
  <h2>Some other place</h2>
  <br clear = "all" />
  <div class = "mypoints">
    <label>
      <input type = "checkbox" class = "chk" value = "1"><span><i class = "fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div>
</body>

Но каждый из этих элементов находится в своем собственном разделе, каждая из них имеет свою собственную строку кода, посмотрите на изображение, как они расположены на моем сайте.

Eden Gandhi Etienne 17.03.2022 14:51

отлично, спасибо за ваш код, но вот 2 картинки, чтобы вы могли лучше понять мою ситуацию, каждая кнопка отдельная и должна иметь свою строку кода. картинка 1 для кнопки 1: awesomescreenshot.com/image/… картинка 2 для кнопки 2: awesomescreenshot.com/image/…

Eden Gandhi Etienne 17.03.2022 15:36

1. Ваш HTML-код недействителен. На странице не может быть нескольких тегов HTML/HEAD/BODY. 2. Если вы хотите, чтобы флажки были в разных местах, а не только в ОДНОМ контейнере, измените const container = document.getElementById('container'); const container = document.getElementById('container'); const checks = container.querySelectorAll('.chk'); на const checks = document.querySelectorAll('.chk');, тогда вы можете разместить флажки где угодно.

mplungjan 17.03.2022 15:46

хорошо, я понимаю, что вы говорите, но скрипт может быть добавлен только к одному элементу за раз, когда я использую скрипт на кнопке выбора всех, он не запускает другой, и другой тоже не работает, когда Добавляю скрипт для них по отдельности, они вроде тоже не работают. Они работают только тогда, когда находятся в одном контейнере.

Eden Gandhi Etienne 17.03.2022 18:20

Хорошо, я сделаю это, я буду ждать тебя. Кроме того, не могли бы вы поделиться им через codepen.io, вы все еще можете поделиться им здесь, если хотите. Однако я буду ждать вашей помощи

Eden Gandhi Etienne 17.03.2022 18:47

Это работает как шарм, я исправляю свой код, как вы предлагаете, и все работает правильно. Я очень ценю вашу помощь, большое спасибо.

Eden Gandhi Etienne 18.03.2022 06:23

Другие вопросы по теме