mousemove
. Приложение работает, всё хорошо, но потом, по некоторой причине, происходит размонтирование и через некоторое время снова монтирование. В таком случае, если не удалить прослушку, будет уже 2 события, что и является утечкой памяти.<script src="" type="module"></script>
. Если среда исполнения node, то в package.json
"type": "module"
. <div class="container">
<div class="image" id="image_1">
<img src="img/1.jpg" alt="1" />
<button class="delete-button">×</button>
</div>
<div class="image" id="image_2">
<img src="img/2.jpg" alt="2" />
<button class="delete-button">×</button>
</div>
<div class="image" id="image_3">
<img src="img/3.jpg" alt="3" />
<button class="delete-button">×</button>
</div>
<div class="image" id="image_4">
<img src="img/4.jpg" alt="4" />
<button class="delete-button">×</button>
</div>
</div>
const buttons = document.quertSelectorAll('.delete-button');
const removeBlock = (target, selector) => {
const element = target.closest(selector);
if (element !== null) {
if (element.id !== '') {
const deletedElements = JSON.parse(localStorage.getItem('deleted-elements')) || [];
deletedElements.push(element.id);
localStorage.setItem('deleted-elements', JSON.stringify(deletedElements));
}
element.remove();
}
}
for (const button of buttons) {
button.addEventListener('click', event => {
event.preventDefault();
removeBlock(event.currentTarget, '.image');
});
}
window.addEventListener('DOMContentLoaded', () => {
const deletedElements = JSON.parse(localStorage.getItem('deleted-elements')) || [];
for (const deletedElement of deletedElements) {
const element = document.quertSelector(`#${deletedElement}`);
if (element !== null) {
element.remove();
}
}
});
const expression = /{{\s+?(\w+)\s+?}}/g;
const pasteParams = (string, params) => {
return string.replace(expression, (match, key) => key in params
? params[key]
: key
);
};
pasteParams('<ul class="{{ className }}"></ul>', {
className: 'my-class'
});
const expression = /.+(?=\/)/;
const array = [
'/siparis/kampanyalar/tumu/cok-karisik-orta-firsati',
'/siparis/kampanyalar/tumu/karisik-ort',
'/siparis'
];
for (const entry of array) {
const match = entry.match(expression);
const parsed = match !== null ? match[0] : null;
console.log(parsed);
}
/*
'/siparis/kampanyalar/tumu'
'/siparis/kampanyalar/tumu'
null
*/
Array.find
, так как он не поддерживается в IE.type URLParamsEntry = [string, string];
class URLParams {
entries: URLParamsEntry[] = [];
constructor(search: string = '') {
const trimmedSearch = search.trim();
if (trimmedSearch.length > 0) {
const pairs = trimmedSearch.replace(/^\?/, '').split('&');
for (const entry of pairs) {
const pair = entry.split('=');
if (pair[0] !== undefined && pair[1] !== undefined) {
const key = pair[0];
const value = decodeURIComponent(pair[1]);
this.entries.push([key, value]);
}
}
}
}
append(key: string, value: string) {
this.entries.push([key, value]);
return this;
}
delete(key: string) {
this.entries = this.entries.filter(entry => entry[0] !== key);
return this;
}
has(key: string) {
const inEntries = this.entries.some(entry => entry[0] === key);
return inEntries;
}
set(key: string, value: string) {
return this.delete(key).append(key, value);
}
get(key: string): string | null {
const entries = this.getAll(key);
return entries.length > 0 ? entries[0] : null;
}
getAll(key: string): string[] {
const entries = this.entries.reduce<string[]>((accumulator, entry) => {
if (entry[0] === key) {
accumulator.push(entry[1]);
}
return accumulator;
}, []);
return entries;
}
toString() {
return this.entries
.map(entry => `${entry[0]}=${encodeURIComponent(entry[1])}`)
.join('&');
}
}
name
. Посмотреть значения можно так:Object.fromEntries([...formData.entries()]);
JSON.stringify(data, null, 4)
(где 4 - количество пробелов в уровне табуляции). Можете использовать другой формат данных, например - CSV. Можете подключить базу данных, какой-нибудь SQLite. Конечно, Вы можете написать свой велосипед:const toJSON = data => {
if (Array.isArray(data)) {
const prepared = data.map(value => JSON.stringify(value));
return `[\n${prepared.join(',\n')}\n]`;
} else {
const prepared = Object.entries(data).map(([key, value]) => (
`${JSON.stringify(key)}: ${JSON.stringify(value)}`
));
return `{\n${prepared.join(',\n')}\n}`;
}
};
const navigation = document.querySelector('.header__navigation');
navigation.addEventListener('click', (event) => {
const activeElements = navigation.querySelectorAll('.active');
for (const activeElement of activeElements) {
activeElement.classList.remove('active');
}
event.target.classList.add('active');
});
const navigation = document.querySelector('.header__navigation');
const items = navigation.querySelectorAll('YOUR_SELECTOR'); // Элементы, у которых должен быть класс active
for (const item of items) {
item.addEventListener('click', () => {
for (const item of items) {
item.classList.remove('active');
}
item.classList.add('active');
});
}
const Button = ({ children, callback, ...props }) => {
return <MainButton {...props} onPress={callback}>{children}</MainButton>;
};
<>
{cart.map(item => (
<div className="catalog-mobile__counter" key={item.product._id}>
<button className="catalog-mobile__minus"></button>
<input type="text" defaultValue={item.quantity || ''} />
<button className="catalog-mobile__plus"></button>
</div>
))}
</>
const today = new Date();
const getWeeks = (month, year) => {
const date = new Date(year, month + 1, 0, 0, 0, 0);
const weeks = [];
const days = date.getDate();
let startWeek = null;
for (let day = 1; day <= days; day++) {
date.setDate(day);
const weekDay = date.getDay();
if (weekDay > 0 && startWeek === null) {
startWeek = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
}
if (weekDay === 0 || day === days) {
weeks.push({
start: startWeek,
end: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0)
});
startWeek = null;
}
}
return weeks;
};
console.log(JSON.stringify(getWeeks(1, 2021), null, 4));
/*
У меня UTC+6, поэтому в датах 6 вечера.
[
{
"start": "2021-01-31T18:00:00.000Z",
"end": "2021-02-06T18:00:00.000Z"
},
{
"start": "2021-02-07T18:00:00.000Z",
"end": "2021-02-13T18:00:00.000Z"
},
{
"start": "2021-02-14T18:00:00.000Z",
"end": "2021-02-20T18:00:00.000Z"
},
{
"start": "2021-02-21T18:00:00.000Z",
"end": "2021-02-27T18:00:00.000Z"
}
]
*/