const getCard = num => cards.find(n => n.id === num);
// ...
const card = getCard(cardRandom(1, 51));id. Может, лучше использовать случайное число как индекс? Типа так:const card = cards[Math.random() * cards.length | 0];
const TYPES = {
1: 'region',
3: 'area',
7: 'street',
};
const newItems = items.map(({ parents_names, parents_levels, ...n }) =>
parents_names.reduce((acc, name, i) => (
acc[TYPES[parents_levels[i]]] = name,
acc
), n)
);
const className = 'element';
const attrName = 'data-attr';
const attrValue = 'this-element';const elem = document.querySelector(`.${className}[${attrName}="${attrValue}"]`);const elems = document.getElementsByClassName(className);
// или
const elems = document.querySelectorAll('.' + className);const elem = Array.prototype.find.call(
elems,
n => n.getAttribute(attrName) === attrValue
);
// или
let elem = null;
for (const n of elems) {
if ((n.attributes[attrName] || {}).value === attrValue) {
elem = n;
break;
}
}
// или
let elem = null;
for (let i = 0; !elem && i < elems.length; i++) {
elem = elems[i].matches(`[${attrName}="${attrValue}"]`) ? elems[i] : elem;
}
Подсказали что правильно сделать через атрибут data-*
data-key, как у тех элементов, по клику на которые блоки надо показывать. По клику хватаете все блоки и показываете те, у которых data-key совпал с кликнутым, остальные скрываете:const key = 'key';
const buttonSelector = `a[data-${key}]`;
const contentSelector = `div[data-${key}]`;$(document).on('click', buttonSelector, function() {
$(contentSelector)
.hide()
.filter((i, n) => n.dataset[key] === this.dataset[key])
.show();
});
// или
document.addEventListener('click', ({ target: t }) => {
if (t = t.closest(buttonSelector)) {
document.querySelectorAll(contentSelector).forEach(n => {
n.hidden = n.dataset[key] !== t.dataset[key];
// или (надо будет в стили добавить .hidden { display: none; })
n.classList.toggle('hidden', n.dataset[key] !== t.dataset[key]);
});
}
});
<div v-if="my_dates['2018-04-23']">{{ myvalue }}</div>myvalue() {
сonst date = this.my_dates['2018-04-23'];
return date ? Number(date.april) + Number(date.may) : null;
}
Имеется довольно большая матрица (чем больше- тем лучше).
Как правильно отрисовать её на странице?
Хотелось бы еще и с нормальной частотой, хотя-бы раз в 50 ms.
не будет ли быстрее преобразовывать матрицу в строку через arr.toString()...
Картинка
const index = str.search(/\d\D*$/);
// или
const index = str.replace(/\D*$/, '').length - 1;
// или
const index = [...str].reduce((max, n, i) => +n === +n ? i : max, -1);
// или
const index = +(Object.entries(str).filter(n => !isNaN(n[1])).pop() || [ -1 ])[0];
// или
let index = str.length;
while (--index >= 0 && !'0123456789'.includes(str[index])) ;
// или
const index = (function get(i) {
return i < 0 || !Object.is(str.charAt(i) * 1, NaN)
? i
: get(~-i);
})(~-str.length);
$('#imgTitle').find('img').remove().end().prepend(...
И еще почему всегда первый элемент в опций виден как undefined ?
И если убрать ng-model то 1-ая опций undefined не будет.
If the viewValue of ngModel does not match any of the options, then the control will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
$('.mod__l').append(function() {
return ({
m1: mod__c1,
m2: mod__c2,
m3: mod__c3,
})[$('.mod__input', this).data('mod')];
});
Помогите пожалуйста понять почему следующий код выводит undefined, а не 5
$(document).mouseup(function (e) { var popup = $('#free_moto_lesson'); if (e.target!=popup[0]&&popup.has(e.target).length === 0){ $('.overlay').fadeOut(); $(popup).fadeOut(); } return false; });
return false.
Нужно ли выносить в отдельный компонент это?
name: 'v-tree',
props: [ 'items' ],<ul v-if="Array.isArray(items) && items.length">
<li v-for="n in items">
{{ n.name }}
<v-tree :items="n.children" />
</li>
</ul>
как сделать, чтобы можно было выбрать максимум 5 дней
кстати когда убираю кусок кода, который переводит на русский, все работает
А как в таком случае сбросить начальную и конечную дату, если нужно другие числа выбрать?
const parentSelector = '.menu';
const indices = [ 0, 1, 4, 8 ];const $elems = $(parentSelector).children().filter(i => indices.includes(i));
// или
const $elems = $(indices.map(n => `> :eq(${n})`).join(', '), parentSelector);const elems = Array.prototype.filter.call(
document.querySelector(parentSelector).children,
(n, i) => indices.includes(i)
);
// или
const elems = document
.querySelector(parentSelector)
.querySelectorAll(indices.map(n => `:scope > :nth-child(${n + 1})`));