$(document).on('click', function(e) {
e.preventDefault();
const $submenu = $(e.target).closest('li').children('.submenu');
$submenu.fadeToggle();
$('.nav li ul').not($submenu).fadeOut();
});
const table = document.querySelector('здесь селектор вашей таблицы');
const idAttr = 'id-object';
const propAttr = 'object-name';const data = Array.prototype.reduce.call(
table.querySelectorAll('table tbody tr'),
(acc, tr) => (
tr.querySelectorAll(`[${propAttr}]`).forEach(function(td) {
this[td.getAttribute(propAttr)] = td.innerText;
}, acc[tr.querySelector(`[${idAttr}]`).getAttribute(idAttr)] = {}),
acc
),
{}
);
// или
const data = {};
for (const { rows } of table.tBodies) {
for (const { cells } of rows) {
const item = data[cells[0].attributes[idAttr].value] = {};
for (let i = 1; i < cells.length; i++) {
const td = cells[i];
item[td.attributes[propAttr].value] = td.textContent;
}
}
}
const className = 'skiptranslate';.for (const { childNodes: n } of document.getElementsByClassName(className)) {
for (let i = n.length; i--;) {
if (n[i].nodeType === Node.TEXT_NODE) {
n[i].remove();
}
}
}document.querySelectorAll(`.${className}`).forEach(n => {
const nodes = [...n.children];
n.innerHTML = '';
n.append(...nodes);
});
function setVal(obj, path, val) {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((p, c) => p[c] = p[c] || {}, obj)[key] = val;
return obj;
}
function replaceObjWithArr(obj) {
if (obj instanceof Object) {
const keys = Object.keys(obj).sort((a, b) => a - b);
obj = keys.every((n, i) => +n === i) ? keys.map(n => obj[n]) : obj;
keys.forEach(n => obj[n] = replaceObjWithArr(obj[n]));
}
return obj;
}const output = replaceObjWithArr(Object
.entries(input)
.reduce((acc, n) => setVal(acc, ...n), {})
);
<button value=" ---> <button data-value=".document.addEventListener('click', ({ target: { dataset: { value } } } ) => {
if (value) {
document.querySelector(`[name="size"][value="${value}"]`).click();
}
});const radios = [...document.querySelectorAll('[name="size"]')];
const buttons = [...document.querySelectorAll('button')];
// можно смотреть на значение data-атрибута
const onClick = e => radios.find(n => n.value === e.target.dataset.value).click();
// или, кликать радиокнопку с тем же индексом, что и у кнопки обычной
const onClick = e => radios[buttons.indexOf(e.target)].click();
buttons.forEach(n => n.addEventListener('click', onClick));
$('a').click(function(e) {
e.preventDefault();
$('html').animate({
scrollTop: $($(this).attr('href')).offset().top,
}, 500);
});
$('#input4').attr('checked', true);checked предназначен для задания дефолтного состояния радиокнопки, вместо него следует использовать одноимённое свойство.<fgroup class="fg1"><div class="fgroup">.const $groups = $('.fgroup').on('change', function(e) {
$groups
.not(this)
.find(`input[value!="${e.target.value}"]`)
.prop('checked', true);
});
const unique = (arr, keys) =>
arr.filter(n => n === arr.find(m => keys.every(k => m[k] === n[k])));const result = unique(arr, [ 'model', 'param1', 'param2' ]);- arr.filter(n => n === arr.find
+ arr.filter((n, i, a) => i === a.findIndexconst unique = function(arr, keys = n => n) {
const picked = new Map;
return arr.filter((...args) => {
const p = []
.concat(keys(...args))
.reduce((acc, k) => acc.set(k, acc.get(k) || new Map).get(k), picked);
return !p.set(this, p.has(this)).get(this);
});
}.bind(Symbol());const result = unique(arr, n => [ n.model, n.param1, n.param2 ]);
+/- с +/0 и -/0, будем считать, что ноль присутствует всегда - у нулевого элемента предыдущего нет, так что для него и запишем нулевую разность. Таким образом, монотонный массив - это такой, у которого неполный комплект различных знаков разностей соседних элементов:const isMonotone = arr =>
arr.every(function(n, i, a) {
return this.add(i && Math.sign(n - a[i - 1])).size < 3;
}, new Set);
const func = () => {
console.log('hello, world!!');
setTimeout(func, 500 + Math.random() * 1000 | 0);
};
func();
const insert = (str, indices, substr = ' ') =>
Array.prototype.reduce.call(
str,
(acc, n, i) => acc + (indices.includes(i) ? substr : '') + n,
''
);
// или
const insert = (str, indices, substr = ' ') => [...indices]
.sort((a, b) => b - a)
.reduce((acc, n) => (acc.splice(n, 0, substr), acc), [...str])
.join('');
// или
const insert = (str, indices, substr = ' ') => []
.concat(0, indices)
.sort((a, b) => a - b)
.map((n, i, a) => str.slice(n, a[i + 1]))
.join(substr);
// или
const insert = (str, indices, substr = ' ') => indices.length
? str.replace(RegExp(indices.map((n, i) => `(?<=^.{${n}})`).join('|'), 'g'), substr)
: str;str = insert(str, [ 1, 3, 6, 8, 10 ]);.
$(window).on('scroll', function() {
const top = $(this).scrollTop();
const index = [ 50, 100, 150, Infinity ].findIndex(n => n > top);
$('.int > div').removeClass('active').eq(index).addClass('active');
}).scroll();
не могу понять, как сделать так, чтобы при втором условии числа выводились от меньшего к большему
const step = Math.sign(p2 - p1);
while (Math.abs(p2 - p1) >= 1) {
p1 += step;
console.log(p1);
}[ p1, p2 ] = p1 > p2 ? [ p2, p1 ] : [ p1, p2 ];
while (p1 < p2) {
p1 += 1;
console.log(p1);
}
const
[ name, price, number ] =
[ 'name', 'price', 'number' ]
.map(n => document.querySelector(`input[name="${n}"]`).value.split(', '));
const arr = name.map((n, i) => ({
name: n,
price: price[i],
number: +number[i],
}));