$(e).one('click', function () {
в следующий раз не вызывать эту функцию при клике на $(e)
})
updateResult(".currentItem", this.owl.currentItem);
var buttonItems = document.querySelectorAll('.button-item'),
index, button;
for (index = 0; index < buttonItems.length; index++) {
button = buttonItems[index];
button.addEventListener('click', function (event) {
console.log('click');
event.preventDefault();
});
}
var buttons = document.querySelectorAll('.button-item'),
index, button;
for (index = 0; index < buttons.length; index++) {
button = buttons[index];
button.addEventListener('click', clickHandler);
button.addEventListener('dblclick', doubleClickHandler);
}
function clickHandler(event) {
console.log('click', this.innerText);
event.preventDefault();
}
function doubleClickHandler(event) {
console.log('doubleclick', this.innerText);
this.removeEventListener('click', clickHandler);
this.removeEventListener('dblclick', doubleClickHandler);
}
one().done(two);
function one() {
var dfd = new $.Deferred();
// Запускаем асинхронную задачу. Например, ajax-запрос.
setTimeout(function () {
var foo = 'bar';
// "Выполняем обещание", передавая в него какую-то информацию.
// Передавать аргументы, разумеется, не обязательно.
dfd.resolve(foo);
}, 2000);
// Возвращаем из функции обещание, на которое могут подписаться другие функции.
// Обратите внимание, этот код выполнится до того, как завершится асинхронная задача.
return dfd.promise();
}
function two(foo) {
// Обрабатываем данные, полученные внутри асинхронной функции one.
console.log('two', foo);
}
one().then(two, onOneError).then(three, onTwoError);
function one() {
var dfd = new $.Deferred();
setTimeout(function () {
console.log('one');
if (Math.round(Math.random() * 10) >= 5)
{
dfd.resolve();
}
else
{
dfd.reject();
}
}, 1000);
return dfd.promise();
}
function two() {
var dfd = new $.Deferred();
setTimeout(function () {
console.log('two');
if (Math.round(Math.random() * 10) >= 5)
{
dfd.resolve();
}
else
{
dfd.reject();
}
}, 1000);
return dfd.promise();
}
function three() {
setTimeout(function () {
console.log('three');
}, 1000);
}
function onTwoError() {
console.log('twoError', arguments);
}
function onOneError() {
console.log('oneError', arguments);
}
one(function () {
two(three)
});
function one(callback) {
console.log('one');
setTimeout(callback, 1000);
}
function two(callback) {
console.log('two');
setTimeout(callback, 1000);
}
function three() {
console.log('three');
}
Как узнать, в каком месте вылезла ошибка?console.error выводит полный стек вызовов со ссылками на конкретные строки конкретных скриптов.
var classes = ['item-id', 'item-title', 'item-price'],
table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
rowIndex, cellIndex, cells, currentRow, currentCell, addToCartCell;
// Пропускаем первую строку, потому что в ней находится заголовок таблицы
for (rowIndex = 1; rowIndex < rows.length; rowIndex++) {
currentRow = rows[rowIndex];
cells = currentRow.getElementsByTagName('td');
for (cellIndex = 0; cellIndex < cells.length; cellIndex++) {
currentCell = cells[cellIndex];
currentCell.setAttribute('class', classes[cellIndex]);
};
addToCartCell = document.createElement("td");
addToCartCell.innerHTML = '<a class="add_item">Добавить в корзину</a>';
currentRow.appendChild(addToCartCell);
};
function getTable() {
return document.getElementById('table')
}
function getRows(table) {
var allTableRows = table.getElementsByTagName('tr'),
rows = [],
index;
// Пропускаем первую строку, потому что в ней находится заголовок таблицы
for (index = 1; index < allTableRows.length; index++) {
rows.push(allTableRows[index]);
}
return rows;
}
function appendAddToCartButton(row) {
var cell = document.createElement("td");
cell.innerHTML = '<a class="add_item">Добавить в корзину</a>';
row.appendChild(cell);
}
function setCellsClasses(row) {
var classes = ['item-id', 'item-title', 'item-price'],
cells = row.getElementsByTagName('td'),
index;
// Обратите внимание, что здесь мы итерируем по классам, а не по ячейкам
// В том случае, если в функции prepareTable кто-то по ошибке
// поменяет местами строки добавления классов и кнопки добавления в корзину
// код не сломается
for (index = 0; index < classes.length; index++) {
cells[index].setAttribute('class', classes[index]);
}
}
function prepareTable() {
var table = getTable(),
rows = getRows(table),
rowIndex, currentRow;
for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
currentRow = rows[rowIndex];
setCellsClasses(currentRow);
appendAddToCartButton(currentRow);
}
}
prepareTable();
var value = '' + 12;
var value = 'б';
if(value.match(/&#/g)) { console.log(value); }
var request = $.get('common.htm');
request.done(function(response) {
var $response = $(response);
// Вместо $response.find(), возможно, придется использовать $response.filter()
// Это зависит от структуры возвращаемого документа
$('#header').html($response.find('.header').html());
$('#menu').html($response.find('.menu').html());
$('#footer').html($response.find('.footer').html());
});
$.fn.setLanguage = function (options) {
options = $.extend({
language: 'ru',
text: this.attr('data-text')
}, options);
var make = function () {
var el = $(this);
$.ajax({
url: options.language + '.json',
dataType: 'json',
success: function (data) {
var html = data[options.text];
if ($.isFunction(options.callback)) {
options.callback(html);
} else {
el.html(html);
}
}
});
};
return this.each(make);
};
var wrapper = $('<div><i>Blah</i> <span>replaced</span> <b>Blah</b></div>');
wrapper.setLanguage({
text: 'login_error',
callback: $.proxy(function (html) {
$(this).find('span').html(html);
}, wrapper),
});
$('body').append(wrapper);