document.getElementByClassName("a")
должно быть document.getElementsByClassName("a")[0]
. Но если таких блоков на странице несколько, то работать этот код корректно не будет. Посмотрите варианты решения вашей задачи здесь.$('span').on('click', function () {
var $el = $(this),
targetID = $el.data('target-id'),
$target = $('#' + targetID);
$target.toggle()
.next('.a')
.toggle();
});
// $(function(){}) и $(document).ready(function(){}) одно и то же
// Нет смысла вкладывать их друг в друга
$(function () {
$(document).ready(function () {
// Если informer может принимать только значения 0 и 1,
// гораздо логичнее сделать эту переменную булевой
var informer = 0;
// Крутые парни ставят точки с запятой в конце выражений
// Конечно, если не хотят потом ловить баги automatic semicolon insertion по ночам
var sfId_Start
var sfId_Target
console.log(informer)
// Зачем у td два обработчика клика?
$('td').click(function () {
init()
++informer;
if (informer > 1) {
informer = 0
}
// if (informer === 1 ) { }
console.log(informer)
});
function init() {
// Зачем делать анонимную функцию, в которой просто вызывается другая функция?
$('td').click(function () {
getId(this);
});
// Зачем эта функция сюда вложена?
function getId(obj) {
var idsf
// Этот код не имеет смысла
// Почему при любом условии в переменную idsf пишется одно и то же значение?
if (informer === 0) {
idsf = $(obj).attr('id')
}
// Зачем проверять, что 1 не равно 0?
if (informer === 1 && informer !== 0) {
idsf = $(obj).attr('id')
}
// Зачем писать одно и то же в обе переменные?
sfId_Start = idsf
sfId_Target = idsf
}
}
})
});
$(".input_has-clear").append("<i class='input__clear'>x</i>");
// Ставим обработчик на событие изменения поля
$('.input__control').on('change', function () {
// Находим родительский блок
$(this).closest('.input_has-clear')
// в родительском блоке находим нужный элемент
.find(".input__clear")
// скрываем или показываем элемент в зависимости от заполненности поля
// обратите внимание, что toggleClass вторым аргументом принимает чисто булевое значение
// поэтому при помощи двойного отрицания приводим строку к нему
// если она пустая - будет false и класс уберется, иначе - добавится
.toggleClass("input__clear_visible", !!$(this).val());
});
$(function() {
$(".input_has-clear").append("<i class='input__clear'>");
// 1. Этот код выполнится один раз при загрузке страницы,
// вам же, наверняка, нужно, чтобы элемент скрывался или показывался
// динамически по мере редактирования поля
// 2. .input_has-clear - это span, у него нет value
if($(".input_has-clear").val() != "") {
// Логика определения скрытия и показа класса неверная
// Если повесить на поле обработчик, то при вводе каждой буквы
// Элемент будет то скрываться, то показываться
$(this).find(".input__clear").toggleClass("input__clear_visible");
}
});
цикл выполняться не хочетВ вашем коде нет ни одного цикла.
function getSomeHtml() {
return $(this).html();
}
for (var p = 0, len = number.length; p < len; p++) {
if (number[p] == 'Свободен') {
number_js[p] = $('.ofice:eq(' + p + ')>.ofice_number>strong').map(getSomeHtml)[0];
for (var i = 0, len = rsrGroups.length; i < len; i++) {
if (number_js[p] == rsrGroups[i].data("room")) {
rsrGroups[i].attr('fill', '#F4DA6C');
}
}
}
}
number_js[p] = $('.ofice:eq(' + p + ')>.ofice_number>strong').first().html();
Может быть можно как то элегантнее решить данную задачу?Разумеется, можно. Достаточно понять, что вам нужно не строки таблицы сортировать, а данные. И уже данные потом рендерить.
methods.init.apply(this, arguments);
You may also pass in a matrix while instantiating the PF.Grid class. It will initiate all the nodes in the grid with the same walkability indicated by the matrix. 0 for walkable while 1 for blocked.
matrix [координата Y (номер строки)] [координата X (номер колонки)]
document.querySelector("#nav-toggle")
if ($(window).width() > 991) {
$("#nav-toggle").on("click", function() {
$(this).toggleClass("active");
});
}
var classes = ['item-id', 'item-title', 'item-price', 'delete-btn'];
$('#sf tr').each(function () {
var $cell = $('<td>').append('<a class="add_item">Добавить в корзину</a>');
$(this).append($cell);
$(this).find('td').each(function (index, element) {
$(element).addClass(classes[index]);
});
});
var classes = ['item-id', 'item-title', 'item-price', 'delete-btn'],
$rows = $('#sf tr').filter(':gt(0)'),
$link = $('<a>').addClass('add_item').text('Добавить в корзину'),
$cell = $('<td>').append($link),
$cells;
$rows.append($cell);
$cells = $rows.find('td');
$cells.each(function (index, cell) {
$(cell).addClass(classes[index % classes.length]);
});
На сколько я поля это фишка асинхронности !?Правильно поняли.
Это получается нужно код выстраивать цепочкой из калбэков ?Необязательно. (для nodejs, понятно, своя специфика, но общие принципы такие же, естественно).
$(document).ready(function () {
var owl = $(".sldr").owlCarousel().data('owlCarousel');
$(window).on('mousewheel', debounce(function (event) {
var direction = event.originalEvent.deltaY < 0 ? 'next' : 'prev';
owl[direction]();
}, 100));
});
function debounce(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function () {
var last = new Date().getTime() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function () {
context = this;
args = arguments;
timestamp = new Date().getTime();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
}
var buttons = document.querySelectorAll('.js-btn-item'),
popups = document.querySelectorAll('.js-products-popup'),
closers = document.querySelectorAll('.js-btn-close'),
index, button, popup, closer;
for (index = 0; index < buttons.length; index++) {
button = buttons[index];
popup = popups[index];
closer = closers[index];
button.addEventListener('click', buttonHandler(popup));
closer.addEventListener('click', closerHandler(popup))
}
function buttonHandler(popup) {
return function (event) {
event.preventDefault();
popup.classList.add('js-popup-show');
}
}
function closerHandler(popup) {
return function (event) {
event.preventDefault();
popup.classList.remove('js-popup-show');
}
}