Пытаюсь так:
let currentIndex = $(".js-practice_button.current").index();
Но значение всегда 0, у какой бы кнопки классcurrent
не присутствовал.
index
по умолчанию определяет индекс элемента среди соседей, а так как у каждой кнопки есть отдельный родитель... Ну да, получаете то, что получаете.const index = $('.js-practice_button.current').closest('li').index();
index
в качестве параметра селектор, то индекс будет определятся не среди соседей, а среди элементов, соответствующих селектору:const index = $('.js-practice_button.current').index('.js-practice_button');
const container = document.querySelector('.js-practices_buttons');
const itemSelector = '.practice_item';
const buttonSelector = `${itemSelector} .js-practice_button`;
const activeClass = 'current';
const activeSelector = `.${activeClass}`;
const index = Array.prototype.findIndex.call(
container.querySelectorAll(buttonSelector),
n => n.classList.contains(activeClass)
);
// или
const { children } = container;
let index = children.length;
while (index-- && !children[index].matches(`:has(${activeSelector})`)) ;
// или
const index =
(el => el ? [...el.parentNode.children].indexOf(el) : -1)
(container.querySelector(`${itemSelector}:has(${activeSelector})`));
// или
let index = -1;
for (
let el = container.querySelector(activeSelector)?.closest(itemSelector);
el;
el = el.previousElementSibling, index++
) ;
const noRepeatingDigits = num => !/(\d).*\1/.test(num);
// или
const noRepeatingDigits = num => -~Math.log10(num) === new Set(`${num}`).size;
// или
const noRepeatingDigits = num => [...'' + num].every((n, i, a) => i === a.indexOf(n));
// или
const noRepeatingDigits = num => String(num)
.split('')
.reduce((acc, n) => (acc[n]++, acc), Array(10).fill(0))
.every(n => n < 2);
// или
const noRepeatingDigits = num =>
!''.match.call(num, /./g).some(function(n) {
return this[n] = Object.hasOwn(this, n);
}, {});
// или
const noRepeatingDigits = num =>
!Array.from(num.toString()).sort().find((n, i, a) => n === a[i + 1]);
arr.splice(0, arr.length, ...arr.filter(noRepeatingDigits));
// или
let numDeleted = 0;
for (const [ i, n ] of arr.entries()) {
arr[i - numDeleted] = n;
numDeleted += !noRepeatingDigits(n);
}
arr.length -= numDeleted;
// или
for (let i = arr.length; i--;) {
if (!noRepeatingDigits(arr[i])) {
arr.splice(i, 1);
}
}
const newArr = arr.filter(noRepeatingDigits);
// или
const newArr = [];
for (const n of arr) {
if (noRepeatingDigits(n)) {
newArr.push(n);
}
}
// или
const newArr = [];
for (let i = 0; i < arr.length; i++) {
if (noRepeatingDigits(arr[i])) {
newArr[newArr.length] = arr[i];
}
}
// или
const newArr = (function xxx(arr, i = 0) {
return i < arr.length
? (noRepeatingDigits(arr[i]) ? [ arr[i] ] : []).concat(xxx(arr, i + 1))
: [];
})(arr);
const arrs = [
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11 ],
];
const result = [];
const max = Math.max(...arrs.map(n => n.length));
const index = Array(arrs.length).fill(0);
for (let i = 0; i < max; i++) {
for (let j = 0; j < index.length; j++) {
if (index[j] < arrs[j].length) {
result[result.length] = arrs[j][index[j]++];
}
}
}
const result = arrs
.reduce((acc, arr) => (
arr.forEach((n, i) => (acc[i] ??= []).push(n)),
acc
), [])
.flat();
const li = Array.prototype.filter.call(
document.querySelector('ul').children,
function(n) {
return this.every(([ k, v ]) => v === n.querySelector(`.${k}`).innerText);
},
Object.entries(items)
);
const li = [];
COLLECT_LI:
for (const n of document.querySelectorAll('li')) {
for (const k in items) {
if (Object.hasOwn(items, k) && items[k] !== n.querySelector('.' + k).textContent) {
continue COLLECT_LI;
}
}
li.push(n);
}
- <script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
+ <script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
import VueRouter from 'vue-router'
<yandex-map
ref="map"
@map-was-initialized="onBoundsChange"
@boundschange="onBoundsChange"
...
>
<ymap-marker
v-for="n in markersData"
...
>
methods: {
onBoundsChange() {
const bounds = this.$refs.map.myMap.getBounds();
this.markersData.forEach(n => {
if (
bounds[0][0] < n.coords[0] && n.coords[0] < bounds[1][0] &&
bounds[0][1] < n.coords[1] && n.coords[1] < bounds[1][1]
) {
// ...
}
});
},
...
$extract = fn($keys, $item) => array_combine($keys, array_map(fn($k) => $item[$k], $keys));
$grouped = [];
$productKeys = [ 'product_id', 'sku', 'quantity' ];
$orderKeys = array_diff(array_keys($arr[0] ?? []), $productKeys);
foreach ($arr as $n) {
$id = $n['order_id'];
$grouped[$id] ??= $extract($orderKeys, $n);
$grouped[$id]['products'][] = $extract($productKeys, $n);
}
метод testemit компонента question не отрабатывает
$emit('testemit')
есть, а вот @testemit="testemit"
отсутствует. site:qna.habr.com <имя-пользователя> <тег> <чего ищем>
tags = Array.from(new Set(data.flatMap(n => n.tags)));
tags.splice(0, tags.length, ...new Set(data.flatMap(n => n.tags)));
const lastEdited = Vue.observable({ instance: null });
props: [ 'value' ],
methods: {
onInput(e) {
this.$emit('input', e.target.value);
lastEdited.instance = this;
},
},
created() {
this.$watch(() => lastEdited.instance, val => {
if (val && val !== this) {
this.$emit('input', '');
}
});
},
beforeDestroy() {
if (lastEdited.instance === this) {
lastEdited.instance = null;
}
},
<input :value="value" @input="onInput">
const eventBus = new Vue();
props: [ 'value' ],
methods: {
onInput(e) {
this.$emit('input', e.target.value);
eventBus.$emit('clear-other-inputs', this);
},
},
created() {
const clear = e => e !== this && this.$emit('input', '');
eventBus.$on('clear-other-inputs', clear);
this.$on('hook:beforeDestroy', () => eventBus.$off('clear-other-inputs', clear));
},
<input :value="value" @input="onInput">
имеется pinia такого вида
<...>
export const useSearchStore = () => {
const { search, updateSearchQuery } = useSearchStore();
Note thatstore
is an object wrapped withreactive
, meaning there is no need to write.value
after getters but, likeprops
insetup
, we cannot destructure it
const useSearchStore = defineStore('search', () => {
const search = ref('');
const setSearch = val => search.value = val;
return { search, setSearch };
});
const searchStore = useSearchStore();
const search = computed({
get: () => searchStore.search,
set: searchStore.setSearch,
});
<input v-model.trim="search">
const searchStore = useSearchStore();
watch(() => searchStore.search, val => console.log(val));
async function getFirstLoadedImage(urls) {
for (const n of urls) {
try {
return await loadImage(n);
} catch (e) {}
}
throw 'ничего загрузить не удалось';
}
const getFirstLoadedImage = (urls, i = 0) => i < urls.length
? loadImage(urls[i]).catch(() => getFirstLoadedImage(urls, -~i))
: Promise.reject('ничего загрузить не удалось');
getFirstLoadedImage(resolutions.map(n => `https://i.ytimg.com/vi/${videoId}/${n}.jpg`))
.then(img => document.body.append(img))
.catch(console.error);
.item-gallery
, и вызываем bind для каждого из них отдельно:document.querySelectorAll('.item-gallery').forEach(n => {
Fancybox.bind(n, '[data-fancybox="single"]', {});
});
Удалился вопрос на этом форуме
у кого-то уже было такое?
Модераторы, ответьте
напишите пожалуйста причину
useEffect(() => setValue(props.value), [ props.value ]);
const rowspan = shards => shards.reduce((acc, n) => acc + n.jobs.length, 0);
<table>
<thead>
<tr>{HEADERS.map(n => <th>{n}</th>)}</tr>
</thead>
<tbody>{
DATA.flatMap(({ cloud, shards }) =>
shards.flatMap((shard, iShard) =>
shard.jobs.map((job, iJob) =>
<tr>
{!iShard && !iJob && <td rowSpan={rowspan(shards)}>{cloud}</td>}
{!iJob && <td rowSpan={shard.jobs.length}>{shard.repository}</td>}
{!iJob && <td rowSpan={shard.jobs.length}>{shard.repository_size_gb}</td>}
<td>{job.job}</td>
<td>{job.job_description}</td>
<td>{job.backup_name}</td>
<td>{job.backup_size_gb}</td>
</tr>
)))}
</tbody>
</table>