const container = document.querySelector('#element');
const itemSelector = '.someclass';
const key = 'id';
const attr = `data-${key}`;
const attrSelector = `[${attr}]`;container.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, function(e) {
e.preventDefault();
let el = this;
while (!(el = el.parentNode).hasAttribute(attr)) ;
console.log(el.getAttribute(attr));
});container.querySelectorAll(attrSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick(e) {
if (e.target.matches(itemSelector)) {
e.preventDefault();
console.log(e.currentTarget.attributes[attr].value);
}
}container.addEventListener('click', e => {
const item = e.target.closest(itemSelector);
if (item) {
e.preventDefault();
console.log(item.closest(attrSelector).dataset[key]);
}
});
По одному работает, если отметить оба, то "Error in v-on handler: "TypeError: Cannot convert undefined or null to object"
validations() {
return {
life: this.property ? {} : { required: v => v },
property: this.life ? {} : { required: v => v },
};
},<div>STATUS: {{ $v.$invalid ? 'ЖОПА' : 'OK' }}</div>
function sort(arr) {
const obj = Object.fromEntries(arr.map(n => [ n.parent, n ]));
const sorted = [];
for (let item = obj['null']; item; item = obj[item.id]) {
sorted.push(item);
}
return sorted;
}function sort(arr, parent = null) {
const item = arr.find(n => n.parent === parent);
return item
? [ item, ...sort(arr, item.id) ]
: [];
}
const formatDateStr = str =>
new Date(str.split(' GMT', 1)[0])
.toLocaleDateString('ru-RU')
.split('.')
.reverse()
.join(', ');const formatDateStr = function(str) {
const [ , month, day, year ] = str.match(/(\S+) (\d+) (\d+)/);
return [ year, this[month], day.padStart(2, 0) ].join(', ');
}.bind(Object.fromEntries(Array.from({ length: 12 }, (_, i) => [
new Date(0, i).toLocaleString('en', { month: 'short' }),
`${i + 1}`.padStart(2, 0)
])));
const includes = (arrs, search) =>
arrs.some(arr => arr.length === search.length && arr.every((n, i) => n === search[i]));function includes(arrs, search) {
COMPARE_ARRAYS:
for (const arr of arrs) {
if (arr.length === search.length) {
for (const [ i, n ] of arr.entries()) {
if (!Object.is(n, search[i])) {
continue COMPARE_ARRAYS;
}
}
return true;
}
}
return false;
}
const columns = [ '#', ...new Set(persons.flatMap(Object.keys)) ];
// или
const columns = [ '#' ].concat(Object.keys(Object.assign({}, ...persons)));document.body.insertAdjacentHTML('beforeend', `
<table>
<thead>
<tr>${columns.map(col => `
<th>${col}</th>`).join('')}
</tr>
</thead>
<tbody>${persons.map((person, i) => `
<tr>${columns.map((col, j) => `
<td>${j ? person[col] ?? '-' : i}</td>`).join('')}
</tr>`).join('')}
</tbody>
</table>
`);const table = document.createElement('table');
table.createTHead().insertRow().append(...columns.reduce((acc, col) => (
(acc[acc.length] = document.createElement('th')).textContent = col,
acc
), []));
persons.forEach(function(person, i) {
columns.forEach(function(col, j) {
this.insertCell().textContent = j ? person[col] ?? '-' : i;
}, this.insertRow());
}, table.createTBody());
document.body.append(table);
$addres.val("Мои данные").change();.change() на [0].dispatchEvent(new Event('input')).
const find = (data, test, key) =>
test(key, data)
? data
: data === Object(data)
? Object.entries(data).reduce((found, n) =>
found !== null ? found : find(n[1], test, n[0])
, null)
: null;function find(data, test) {
for (const stack = [ [ , data ] ]; stack.length;) {
const [ k, v ] = stack.pop();
if (test(k, v)) {
return v;
} else if (v instanceof Object) {
stack.push(...Object.entries(v).reverse());
}
}
return null;
}const value = find(вложенный_объект, k => k === 'ключ');
const $section = $('.section').on('click', () => $section.addClass('opened'));
$section.find('.close').on('click', e => {
e.stopPropagation();
$section.removeClass('opened');
});
// или
const section = document.querySelector('.section');
section.addEventListener('click', () => section.classList.add('opened'));
section.querySelector('.close').addEventListener('click', e => (
e.stopPropagation(),
section.classList.remove('opened')
));const $section = $('section').click(e => {
$section.toggleClass('opened', !$(e.target).is('.close'));
});
// или
document.querySelector('.section').addEventListener('click', e => {
e.currentTarget.classList.toggle('opened', !e.target.matches('.close'));
});
Object.values(orders.reduce((acc, n) => {
const date = n.date.split(' ')[0];
((acc[date] ??= {
date,
documents: {},
}).documents[n.docTypesName] ??= {
date: n.date,
docId: n.docId,
docTypesName: n.docTypesName,
products: [],
}).products.push({
name: n.name,
price: n.price,
image: n.image,
qunatity: n.quantity,
});
return acc;
}, {})).map(n => (n.documents = Object.values(n.documents), n))
async function test() {
let result = null;
do {
result = await camel() || await new Promise(r => setTimeout(r, 1000));
} while (!result);
return result;
}
import { Lazy } from 'swiper';. Этого вы не сделали.SwiperCore.use([ Lazy ]);. Этого вы не сделали.<Swiper lazy={true}>. Этого вы не сделали.swiper-lazy, атрибут src заменить на data-src. Ну, хоть это у вас есть.
state: {
characters: [],
page: 0,
pages: 0,
},
mutations: {
setCharacters: (state, { characters, pages, page }) =>
Object.assign(state, { characters, pages, page }),
},
actions: {
async fetchCharacters({ commit }, page = 1) {
try {
const { data: { info, results } } = await axios.get(`${BASE_URL}?page=${page}`);
commit('setCharacters', {
page,
pages: info.pages,
characters: results,
});
} catch (e) {
console.error(e);
}
},
},computed: {
currentPage: {
get() {
return this.$store.state.page;
},
set(page) {
this.$store.dispatch('fetchCharacters', page);
},
},
},<el-pagination
v-model:current-page="currentPage"
:page-count="$store.state.pages"
layout="prev, pager, next"
background
/>
const flatten = arr => [].concat(...arr.map(n => Array.isArray(n) ? flatten(n) : n));
// или
function flatten(arr) {
const result = [];
for (const n of arr) {
if (n?.constructor === Array) {
[].push.apply(result, flatten(n));
} else {
result.push(n);
}
}
return result;
}function flatten(arr) {
const result = [];
const stack = [];
for (let i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i] instanceof Array) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i] ];
} else {
result.push(arr[i]);
}
}
return result;
}
// или
function flatten([...arr]) {
for (let i = 0; i < arr.length; i++) {
const n = arr[i];
if (n?.[Symbol.iterator] && typeof n !== 'string') {
arr.splice(i--, 1, ...n);
}
}
return arr;
}