function addClickListeners(buttonsSelector, dialogSelector) {
const buttons = document.querySelectorAll(buttonsSelector);
const dialog = document.querySelector(dialogSelector);
buttons.forEach(n => n.addEventListener('click', e => {
e.preventDefault();
dialog.style.display = 'block';
}));
dialog.addEventListener('click', ({ target }) => {
if (target.classList.contains('popup-close')) {
document.getElementById('name_1').disabled = true;
document.getElementById('phone_1').disabled = true;
dialog.style.display = 'none';
} else if (!target.closest('.popup-content')) {
dialog.style.display = 'none';
}
});
}
addClickListeners('header .contacts a', '.popup-call');
addClickListeners('.sentence-btn', '.popup-discount');
addClickListeners('.check-btn', '.popup-check');
document.addEventListener('click', function(e) {
const heading = e.target.closest('.panel-heading');
if (heading) {
e.preventDefault();
heading.closest('.panel-group').querySelectorAll('.panel-collapse').forEach(n => {
n.classList[n === heading.nextElementSibling ? 'toggle' : 'remove']('in');
});
}
});
const result = array1.filter(n => !array2.some(m => m.name === n.name));function diff(data1, data2, key = n => n) {
const result = [];
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set(Array.from(data2, getKey));
for (const n of data1) {
if (!keys.has(getKey(n))) {
result.push(n);
}
}
return result;
}// ваш случай
const result = diff(array1, array2, 'name');
// есть и другие варианты применения
diff([ 1, 2, 3, 4, 5 ], [ 1, 2, 3 ]) // [4, 5]
diff(Array(10).keys(), Array(7).keys()) // [7, 8, 9]
diff('abcde', 'ACE', n => n.toLowerCase()) // ['b', 'd']
const selector = '.all-blocks.color-blocks .block';
const idSuffix = '_2';$(selector).attr('id', function(i, id) {
return $(this).hasClass(id) ? id + idSuffix : id;
});document.querySelectorAll(selector).forEach(n => {
n.id += n.classList.contains(n.id) ? idSuffix : '';
});
.active .block {
border: 1px solid red;
color: red;
}
.active .under-box-text {
display: none;
}
.active .invisible {
display: block;
}const itemSelector = '.wrapper';
const buttonSelector = '.block, .link';
const activeClass = 'active';$(itemSelector).on('click', buttonSelector, e => {
$(e.delegateTarget).toggleClass(activeClass);
});
// или
document.querySelectorAll(itemSelector).forEach(function(n) {
n.querySelectorAll(buttonSelector).forEach(m => m.addEventListener('click', this));
}, e => e.currentTarget.closest(itemSelector).classList.toggle(activeClass));
// или
document.querySelectorAll(itemSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick(e) {
const button = e.target.closest(buttonSelector);
if (button) {
this.classList.toggle(activeClass);
}
}
// или
document.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
const item = button && button.closest(itemSelector);
item && item.classList.toggle(activeClass);
});
запрос_1()
.then(результат_1 => Promise
.all(результат_1.map(запрос_2))
.then(результат_2 => результат_1.map((значение_1, i) => ({
значение_1: значение_1,
значение_2: результат_2[i],
})))
)
.then(console.log)
const getDayName = (day, lang) => (({
en: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
ru: [ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота' ],
})[lang] || [])[day - (7 * Math.floor(day / 7))];
getDayName(5, 'en') // 'Friday'
getDayName(7, 'ru') // 'Воскресенье'
getDayName(-19, 'ru') // 'Вторник'
getDayName(4, 'fr') // undefinedconst getDayName = (day, lang) =>
new Date(2001, 0, ((day % 7) + 7) % 7).toLocaleString(lang, { weekday: 'long' });
getDayName(4, 'fr') // 'jeudi'
getDayName(36, 'de') // 'Montag'
// можно посмотреть количество ключей
const isEmpty = x => !Object.keys(x || {}).length;
// или перебирать свойства, пока не встретится собственное
function isEmpty(x) {
for (const k in x) if (x.hasOwnProperty(k)) {
return false;
}
return true;
}isEmpty() // true
isEmpty(null) // true
isEmpty(666) // true
isEmpty('') // true
isEmpty([]) // true
isEmpty({}) // true
isEmpty([ 187 ]) // false
isEmpty({ xxx: 69 }) // false
isEmpty('hello, world!!') // false
await Promise.all([ one(), query().then(commit) ])await Promise.all([ one(), query().then(r => (commit(), r)) ])
const data = Array.from(
document.querySelectorAll('.bigDiv'),
n => Array.from(
n.querySelectorAll('.smallDiv'),
m => m.innerText
)
);const data = [];
for (const n of document.getElementsByClassName('bigDiv')) {
const row = data[data.length] = [];
for (const m of n.children) {
row[row.length] = m.innerHTML;
}
}const data = Array.prototype.reduce.call(
document.getElementsByClassName('smallDiv'),
(acc, n) => (
n.previousElementSibling || acc.push([]),
acc[~-acc.length].push(n.textContent),
acc
),
[]
);
.hidden {
display: none;
}const checkbox = document.querySelector('.block50 input');
const block = document.querySelector('.block83');
const onChange = e => block.classList.toggle('hidden', !e.target.checked);
checkbox.addEventListener('change', onChange);список скрывается только после того, когда поставишь и уберешь галочку
<div class="block83 hidden">checkbox.dispatchEvent(new Event('change'));body:not(:has(.block50 :checked)) .block83 {
display: none;
}
document.querySelector('#myselect').addEventListener('change', function(e) {
const select = this;
// или
// const select = e.target;
// const select = e.currentTarget;
const [ option ] = select.selectedOptions;
// или
// const option = select[select.selectedIndex];
// const option = select.querySelector(`[value="${select.value}"]`);
// const option = select.querySelector('option:checked');
// const option = [...select.options].find(n => n.selected);
const forAttr = option.getAttribute('for');
// или
// const forAttr = option.attributes.for.value;
document.querySelector('#mydiv').innerText = `Вес брутто*: ${forAttr}`;
});
Promise
.all([...img].map(n => new Promise(r => n.complete ? r() : n.onload = r)))
.then(() => img.forEach(n => n.style.position = 'absolute'));
const intervals = [ 1000, 2000, 500, 3000 ];
let interval = -1;
function newsRotator() {
const $news = $('.news');
const $hidden = $news.not(':visible');
const $next = $hidden.eq(Math.random() * $hidden.length | 0);
$news.hide();
$next.show();
interval = (interval + 1) % intervals.length;
setTimeout(newsRotator, intervals[interval]);
}
newsRotator();
for(i = 0
i должна быть объявлена. Погуглите, что происходит, если выполнить присваивание необъявленной переменной.i<= n;newArr[i] = a[i];function arrayNtimes(a, n) {
const result = [];
for (let i = 0; i < a.length * n; i++) {
result[i] = a[i % a.length];
}
return result;
}const arrayNtimes = (a, n) => Array(n).fill(a).flat();