Продолжая мой предыдущий пост, на этот раз мне нужно добавить цвет фона кнопки при нажатии.
Я пробовал btn\[i\].style.background = "#000000"
, но безуспешно.
<script>
const btns = document.getElementById("container");
const textBtn = [ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10"]
for(i=0; i <textBtn.length;i++){
btns.insertAdjacentHTML('beforeend', `<button class = "allbuttons" value = "${textBtn[i]}">${textBtn[i]}</button>`);
}
const btn = document.querySelectorAll(".allbuttons")
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function (event) {
document.getElementById("result").innerHTML = event.target.value;
btn[i].style.background = "#000000";
});
}
</script>
<div id = "container"></div>
<h2 class = "allbuttons" id = "result">Item 1</h2>
event.target.("value")
неверно, и у вас нет элемента result
.
Извините за ошибки в посте, я добавил содержание, которое вы говорите, спасибо!
Вот как бы я к этому подошел.
container
. Мы можем использовать делегирование событий, чтобы перехватывать события из дочерних элементов контейнера по мере того, как они «пузырятся» в DOM, что означает, что нам не нужно прикреплять слушателей к каждой кнопке.container
, мы вызываем функцию handleClick
, которая проверяет, был ли этот элемент элементом кнопки. Обновляем textContent result
, а затем добавляем к кнопке «черный» класс.// Cache the elements
const container = document.getElementById('container');
const result = document.getElementById('result');
// Add one listener to the container
container.addEventListener('click', handleClick);
const textBtns = [ 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10'];
// `map` over the array to produce a joined array of HTML strings
const html = textBtns.map(btn => {
return `
<button
class = "allbuttons"
value = "${btn}"
>${btn}</button>
`;
}).join('');
// Set the HTML of the container once
container.innerHTML = html;
// Check to see that the clicked element is
// a button, and then update the textContent of `result`
// remove all the "black" classes from the buttons,
// and add a "black" class to the clicked button.
function handleClick(e) {
if (e.target.matches('button')) {
result.textContent = e.target.value;
const buttons = container.querySelectorAll('button');
buttons.forEach(button => button.classList.remove('black'));
e.target.classList.add('black');
}
}
.black { background-color: black; }
<div id = "container"></div>
<h2 class = "allbuttons" id = "result">Item 1</h2>
это фантастика, это сработало отлично. Если в другом случае, как мне сделать так, чтобы измененный цвет оставался только на последней нажатой кнопке без изменения других?
Я добавляю 2 дополнительные строки в функцию. Первый захватывает все кнопки в контейнере, а второй снимает черный класс с каждой из них. @MauricioRios (думаю, это то, что вы имели в виду).
«SyntaxError: отсутствует } в составном операторе» — возможно, сначала это исправьте.