handleTdClick(item) {{this.state.rows.map((row, rowIndex) => (
<tr>
{row.map((item, colIndex) => (
<td
onClick={this.onTdClick}
data-row={rowIndex}
data-col={colIndex}
className={item ? 'not-empty' : 'empty'}
>
{item}
</td>
))}
</tr>
))}onTdClick = ({ target: { dataset: d } }) => {
const row = +d.row;
const col = +d.col;
this.setState(({ rows }) => ({
rows: rows.map((n, i) =>
i === row
? n.map((m, j) => j === col ? +!m : m)
: n
)
}));
}
const addEntry = (state, action) => {
const cards = [...state.cards];
const index = cards.findIndex(n => n.id === action.id);
const card = {...cards[index]};
card.entries = [ ...card.entries, { id: Math.random().toString(36).substring(7) } ];
cards[index] = card;
return { cards };
};
document.querySelector('.animate-all').addEventListener('click', e => {
e.target.hidden = true;
forEachWithDelay(
document.querySelectorAll('[data-color]'),
500,
el => el.parentNode.style.backgroundColor = el.dataset.color
);
});function forEachWithDelay(arr, delay, callback) {
Array.prototype.forEach.call(arr, (n, i) => {
setTimeout(callback, (i + 1) * delay, n);
});
}function forEachWithDelay(arr, delay, callback) {
(function next(i) {
if (i < arr.length) {
setTimeout(() => {
callback(arr[i]);
next(-~i);
}, delay);
}
})(0);
}function forEachWithDelay(arr, delay, callback) {
let i = -1;
const intervalId = setInterval(() => {
if (++i < arr.length) {
callback(arr[i]);
} else {
clearInterval(intervalId);
}
}, delay);
}
const setBgColor = (el, color) =>
el.style.backgroundColor = color;
// или
el.style.setProperty('background-color', color);
// или
el.style.cssText += `background-color: ${color}`;
// или
el.setAttribute('style', `background-color: ${color}`);document.addEventListener('click', ({ target: t }) => {
const { color } = t.dataset;
if (color) {
for (; t.tagName !== 'LI'; t = t.parentNode) ;
setBgColor(t, color);
}
});
// или
document.querySelectorAll('[data-color]').forEach(function(n) {
n.addEventListener('click', this);
}, function() {
setBgColor(this.closest('li'), this.getAttribute('data-color'));
});
$('#production, #col, .pay, [name="size"]').on('input', recalcPrice);
recalcPrice();
function recalcPrice() {
const price = [
$('#production').val(),
...$('.pay:checked').get().map(n => n.value),
$('[name="size"]:checked').val(),
].reduce((acc, n) => acc + (n | 0), 0);
$('#final_price').html(price * ($('#col').val() | 0));
}
const title = document.getElementById('title');
title.innerHTML = Array.from(title.innerText, n => `<span>${n}</span>`).join('');const title = document.querySelector('#title');
title.innerHTML = title.textContent.replace(/./g, '<span>$&</span>');
Проблема в том, что компонент Form, некоторые элементы которого зависят от стейта - не ререндерятся.
i в момент выполнения document.getElementsByClassName("desc")[i] будет тем же, что и в момент выполнения acc[i].addEventListener есть ни на чём не основанная фантазия, не соответствующая реальности.i в заголовке цикла с помощью let - тогда да, работать будет..desc нет необходимости. Можно от кликнутой кнопки подняться до .tab-pane и там переключить класс, который изменит видимость .desc:.active .desc {
display: block;
}const itemSelector = '.tab-pane';
const buttonSelector = `${itemSelector} .material_info`;
const activeClass = 'active';
const toggle = el => el.closest(itemSelector).classList.toggle(activeClass);
// слушаем клики на кнопках
document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => toggle(e.target));
// или, применяем делегирование - назначаем обработчик один раз общему предку кнопок,
// внутри проверяем, где случился клик
document.addEventListener('click', ({ target: t }) => {
if (t = t.closest(buttonSelector)) {
toggle(t);
}
});
return abs(($a['value'] - $c_v) - ($b['value'] - $c_v)); // тут возможно бред - уже изменял 100000 раз и запутался
usort($arr, function($a, $b){
$c_v = 2.6;
return ceil(abs($a['value'] - $c_v) - abs($b['value'] - $c_v));
});
const random = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;function createMatrix(rows, cols, min, max) {
const matrix = [];
for (let i = 0; i < rows; i++) {
matrix.push([]);
for (let j = 0; j < cols; j++) {
matrix[i][j] = random(min, max);
}
}
return matrix;
}
// или
const createMatrix = (rows, cols, min, max) =>
Array.from({ length: rows }, () =>
Array.from({ length: cols }, () =>
random(min, max)
)
);function outputMatrix(matrix, el) {
const table = document.createElement('table');
matrix.forEach(function(n) {
const tr = this.insertRow();
n.forEach(m => tr.insertCell().textContent = m);
}, table.createTBody());
el.appendChild(table);
}
// или
function outputMatrix(matrix, el) {
el.insertAdjacentHTML('beforeend', `
<table>
<tbody>${matrix.map(n => `
<tr>${n.map(m => `
<td>${m}</td>`).join('')}
</tr>`).join('')}
</tbody>
</table>
`);
}outputMatrix(createMatrix(5, 5, 10, 30), document.body);
что-то мне подсказывает, что сам подход не верен
возможно вообще стоит разделить all и остальной список чекбоксов?