const items = [];
items["one"]=1;
items["two"]=1;
if(items["one"]) console.log("Есть"); else console.log("Нет");
delete items["one"];
if(items["one"]) console.log("Есть"); else console.log("Нет");
// либо
items["one"]=0;
if(items["one"]) console.log("Есть"); else console.log("Нет");
Мне нужно сделать так, что если человек постоянно кликает по кнопке, то обновлять таймер
if (index > 0) {
$(this).remove();
}
if (items[name]) return;
if (items[name]) return;
if (items[name]) {
// остановка анимации таймера и запуск заново
} else {
// код первого запуска таймера.
}
<div class="-notification -f-medium error" style="opacity: 1; top: 0px;">
<div class="-notification-close site-icons-close"></div>
<div class="-icon-font- -f-large -notification-icon inline-block"></div>
<div class="inline-block -notification-text">Товара "<?php echo $product_data->get_name(); ?>" нет в наличии в количестве 2 шт.</div>
<div class="-notification-timer"></div>
</div>
var Item = function(data) {
this.data = data;
}
var items = {};
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: m_notice_click.ajax_url,
data: dataMnot,
dataType: 'json',
success: function(data) {
$('body').append('<div class="-notification-box"></div>');
$('.-notification-box').each(function(index, value) {
if (index > 0) {
$(this).remove();
if (items[data]) return;
var item = new Item(data);
items[data] = item;
$('.-notification-box').append(data);
}
var notTime = $('.-notification');
if ($('.-notification-timer').width()) {
$('.-notification-timer').stop(true, true).animate({width: 0}, {duration: 5000, complete: function() { $('.-notification-timer').css("width", "100%"); $(this).parent().remove(); delete items[data]; }});
}
});
}
});
});
<div class="notice__timer" data-name="${name}"></div>
<div class="-notification -f-medium error" style="opacity: 1; top: 0px;">
<div class="-notification-close site-icons-close"></div>
<div class="-icon-font- -f-large -notification-icon inline-block"></div>
<div class="inline-block -notification-text">Товара "<?php echo $product_data->get_name(); ?>" нет в наличии в количестве 2 шт.</div>
<div class="-notification-timer"></div>
</div>
`<div class="notice__timer" data-name="${name}"></div>`
{
id: SOME_ID,
html: '<div class="-notification -f-medium error" style="opacity: 1; top: 0px;">
<div class="-notification-close site-icons-close"></div>
<div class="-icon-font- -f-large -notification-icon inline-block"></div>
<div class="inline-block -notification-text">Товара "<?php echo $product_data->get_name(); ?>" нет в наличии в количестве 2 шт.</div>
<div class="-notification-timer"></div>
</div>'
}
<div class="inline-block -notification-text">Товара "<?php echo $product_data->get_name(); ?>" нет в наличии в количестве 2 шт.</div>
`<div class="notice__timer" data-name="${name}"></div>`
const items = [];
// ...............
// ...............
// добавляем контейнер для таймеров в DOM если его не существует
if (!$('.timers_container').length) {
$('body').append('<div class="timers_container"></div>');
}
// создаем JQuery объект из полученного HTML
let $html = $(data);
// получаем имя = текст из блока .inline-block.-notification-text
let name = $html.find('.inline-block.-notification-text').text();
// добавляем в items данный name
items[name] = 1;
// устанавливаем аттрибут data-name в полученном "таймере"
$html.find('.-notification-timer').data('name', name);
// ...
// добавляем "таймер" в контейнер
$('.timers_container').append($html);
// стартуем таймер
// ...
'<div class="-notification -f-medium error" style="opacity: 1; top: 0px;">
<div class="-notification-close site-icons-close"></div>
<div class="-icon-font- -f-large -notification-icon inline-block"></div>
<div class="inline-block -notification-text">Товара "' + data.msg + '" нет в наличии в количестве 2 шт.</div>
<div class="-notification-timer"></div>
</div>'
тогда наверно проще формировать просто текст на сервере и вставлять его в вёрстку в js уже ?
<div class="product-item preview-size-250" id="item43132612">
<div class="background"></div>
<div class="wrapper" style="width:250px"><a href="http://vintagetechnics.ru/products/43132612">
<div class="-relative item-image" style="height:190px"><img
src="//i.siteapi.org/LetPQXB1TG_5FEafDIx2LhOg49s=/0x0:1619x1080/fit-in/250x190/center/top/filters:fill(transparent):format(png)/8292488b394caa9.s.siteapi.org/img/1xdusdzfulgk0okok4c0ogg4ocgow4" class="product-preview-img"
alt="Проигрыватель винила Sony TTS-6000 + Sony PUA-7" title="Проигрыватель винила Sony TTS-6000 + Sony PUA-7" width="250" height="190"></div>
</a>
<div class="product-link -text-center"><a href="http://vintagetechnics.ru/products/43132612">Проигрыватель винила Sony TTS-6000 + Sony PUA-7</a><a href="#" class="cart-btn">
<div class="overlay"></div>
<div class="grid-7-sprite-cart-product cart-product"></div>
</a></div>
<div class="-text-center ">
<div class="product-price"><span class="price"><span class="product-price-data" data-cost="200000">
200 000 руб.
</span></span></div>
</div>
</div>
</div>
<div class="product-item preview-size-250" id="item43132612">
<a href="#" class="cart-btn">
function() {
return e.addToCart(this, !0)
}
addToCart: function(e, t, i) {
var n = 1 == t ? $(e).parents(".product-item") : $(e).parents(".item-content"),
o = i || [];
if (n.length > 0) {
var a = $(n).attr("id").replace("item", "") || 0,
r = t && !$(e).hasClass("js-cart-btn") ? void 0 : e;
this.push({
itemId: a,
num: 1,
getcart: 1,
button: r,
productParams: o
})
}
return !1
}
n = 1 == t ? $(e).parents(".product-item") : $(e).parents(".item-content")
n = $(e).parents(".product-item")
<div class="product-item preview-size-250" id="item43132612">
var a = $(n).attr("id").replace("item", "") || 0,
data-product_id="370"
var ntNotification = {
templates: {},
notifications: [],
getTemplate: function(e, t) {
var i = this;
this.templates[e] ? t(i.templates[e]) : $.get("/html/ru_RU/utils/notification.html", function(n) {
i.templates[e] = n, t(i.templates[e])
})
},
getTop: function(e) {
return parseInt(e.css("top").replace("px", ""))
},
moveAll: function(e, t) {
var i = this;
_.forEach(i.notifications, function(n, o) {
if (o >= e)
if (e != o) {
var a = i.notifications[o - 1].elm;
t = t + a.outerHeight() + 5, n.elm.animate({
top: t + "px"
}, 200)
} else n.elm.animate({
top: t + "px"
}, 200)
})
},
deleteNotification: function(e, t) {
var i = this,
n = _.indexOf(i.notifications, e),
o = i.getTop(e.elm);
e.timeout && clearTimeout(e.timeout), i.notifications = _.without(i.notifications, e), e.elm.stop(!0, !0), t ? e.elm.animate({
left: e.elm.width() + "px",
opacity: 0
}, 200, function() {
e.elm.remove(), i.moveAll(n, o)
}) : e.elm.animate({
top: o - e.elm.outerHeight() + "px",
opacity: 0
}, 200, function() {
e.elm.remove(), i.moveAll(n, o)
})
},
shake: function(e) {
for (var t = 0; t < 6; t++) $(e).animate({
"margin-left": t % 2 == 0 ? 5 : -5
}, {
duration: 70,
queue: !0
});
$(e).animate({
"margin-left": 0
}, 70)
},
getPageX: function(e) {
var t = 0;
if ("touchstart" == e.type || "touchmove" == e.type || "touchend" == e.type || "touchcancel" == e.type) {
t = (e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]).pageX
} else "mousedown" != e.type && "mouseup" != e.type && "mousemove" != e.type && "mouseover" != e.type && "mouseout" != e.type && "mouseenter" != e.type && "mouseleave" != e.type || (t = e.pageX);
return t
},
show: function(e, t, i) {
var n = this,
o = CryptoJS.SHA1(t).toString(),
a = _.findWhere(n.notifications, {
id: o
}),
r = !_.isUndefined(i) && i;
if (a) {
if (a.elm.stop(!0, !0), n.shake(a.elm), a.timeout) {
clearTimeout(a.timeout);
var s = a.elm.find(".-notification-timer");
s.stop(!0, !0), s.css({
width: ""
}), s.animate({
width: 0
}, a.time), a.timeout = setTimeout(function() {
n.deleteNotification(a)
}, a.time)
}
} else this.getTemplate(e, function(a) {
window.view && window.view.translate && (t = window.view.translate(t));
var s = {
id: o,
elm: $(_.template(a)({
type: e,
message: t,
hasTimer: r
}))
};
if (s.elm.data("id", o), n.notification_box || (n.notification_box = $('<div class="-notification-box"></div>'), $(document).on("click", ".-notification-close, .-notification-box .-notification-icon", function() {
var e = _.findWhere(n.notifications, {
id: $(this).parent().eq(0).data("id")
});
e && n.deleteNotification(e)
}), $(document).on("touchstart", ".-notification", function(e) {
var t = _.findWhere(n.notifications, {
id: $(this).data("id")
});
t.elm.css("left", 0);
var i = n.getPageX(e),
o = t.elm.offset();
$(document).on("touchmove.notification", function(e) {
var a = n.getPageX(e),
r = a - i;
r > 0 ? t.elm.css({
left: r + "px"
}) : o.left < a ? i = a : $(document).off("touchmove.notification touchend.notification"), r > 100 && ($(document).off("touchmove.notification touchend.notification"), n.deleteNotification(t, !0))
}), $(document).on("touchend.notification", ".-notification", function() {
t.elm && t.elm.css({
left: 0
}), $(document).off("touchmove.notification touchend.notification")
})
}), n.notification_box.css({
top: 0
}), $("body").append(n.notification_box)), s.elm.css({
opacity: 0,
top: 0
}), n.notification_box.append(s.elm), 0 != n.notifications.length) {
5 == n.notifications.length && n.deleteNotification(n.notifications[n.notifications.length - 1]);
var c, d = function() {};
_.forEach(n.notifications, function(e, t) {
if (t == n.notifications.length - 1 && (d = function() {
s.elm.animate({
opacity: 1
}, {
duration: 100,
queue: !0
})
}), 0 != t) {
var i = n.notifications[t - 1].elm;
c = c + i.outerHeight() + 5, e.elm.animate({
top: c + "px"
}, 100, d)
} else c = s.elm.outerHeight() + 5, e.elm.animate({
top: c + "px"
}, 100, d)
})
} else s.elm.animate({
opacity: 1
}, 100);
n.notifications.unshift(s), r && (s.time = i, s.elm.find(".-notification-timer").animate({
width: 0
}, i), s.timeout = setTimeout(function() {
n.deleteNotification(s)
}, s.time))
})
},
showError: function(e, t) {
t = _.isUndefined(t) ? 5e3 : t, this.showMessage(e, "error", t)
},
showWarning: function(e, t) {
t = !0 === t && 5e3 || t, this.showMessage(e, "warning", t)
},
showSuccess: function(e, t) {
t = _.isUndefined(t) ? 5e3 : t, this.showMessage(e, "success", t)
},
showMessage: function(e, t, i) {
var n = this;
if (t = t || "error", i = _.isUndefined(i) ? "warning" == t ? 0 : 5e3 : i, /^\/[a-z]+/.test(e)) {
var o = $("body").data("lang");
$.get("/html/" + o + e, function(e) {
n.show(t, e, i)
})
} else n.show(t, e, i)
}
};
//........
o = CryptoJS.SHA1(t).toString(),
a = _.findWhere(n.notifications, {
id: o
})
//........ потом навешиваются
s.elm.data("id", o)
// далее использование:
$(document).on("click", ".-notification-close, .-notification-box .-notification-icon", function() {
var e = _.findWhere(n.notifications, {
id: $(this).parent().eq(0).data("id")
});
// ...
$(document).on("touchstart", ".-notification", function(e) {
var t = _.findWhere(n.notifications, {
id: $(this).data("id")
});
const items = [];
// ...............
// ...............
// добавляем контейнер для таймеров в DOM если его не существует
if (!$('.timers_container').length) {
$('body').append('<div class="timers_container"></div>');
}
// создаем JQuery объект из полученного HTML
let $html = $(data);
// получаем имя = текст из блока .inline-block.-notification-text
let name = $html.find('.inline-block.-notification-text').text();
// добавляем в items данный name
items[name] = 1;
// устанавливаем аттрибут data-name в полученном "таймере"
$html.find('.-notification-timer').data('name', name);
// ...
// добавляем "таймер" в контейнер
$('.timers_container').append($html);
// стартуем таймер
// ...
// создаем JQuery объект из полученного HTML
let $html = $(data);
// получаем имя = текст из блока .inline-block.-notification-text
let name = $html.find('.inline-block.-notification-text').text();
// добавляем в items данный name
items[name] = 1;
// устанавливаем аттрибут data-name в полученном "таймере"
$html.find('.-notification-timer').data('name', name);
// ...
// добавляем "таймер" в контейнер
$('.timers_container').append($html);
// стартуем таймер
добавьте к обьекту Items поле в котором вы будете хранить таймер, и через это поле получайте доступ к нему. Тогда идентификатор не будет нужен
а если без id, то необходимо составлять сложный объект , хранить ссылки на DOM блоков-контейров сообщений и работать с этим объектом, как-то так.
let Item = function(name, timer) {
this.name = name;
this.timer = timer;
}
const items = [];
// ....
// ....
// создаем JQuery объект из полученного HTML
let $html = $(data);
// подключите библиотеку отсюда
// https://www.queness.com/code-snippet/6523/generate-md5-hash-with-javascript
// получаем имя = текст из блока .inline-block.-notification-text
let name = calcMD5($html.find('.inline-block.-notification-text').text());
// передаем в объект Item хэш текста сообщения и ссылку НА таймер
items[name] = new Item(name, $html.find('.-notification-timer'));
// либо просто в массиве
items[name] = $html.find('.-notification-timer');
// ...
// соответственно по тексту сообщения/хеша,
// получаем элемент из списка объектов, хотя не знаю зачем так можно вообще просто:
// items[name] = $html.find('.-notification-timer');
// т.е. опять голый массив.
function startTimer(name) {
let $timer = items[name]; // либо если объект - items[name].timer
$timer.stop();
$timer.css("width", "100%");
$timer.animate(
{width: 0},
{duration: 10000,
complete: function() {
$(this).closest('.notice__info').remove();
delete items[name];
console.log(`Удален ${name}`);
}
}
);
}
$(document).on('click', '.notice__delete', function() {
let $timer = $(this).siblings().find('.notice__timer');
let name = calcMD5($(this).siblings().find('.inline-block.-notification-text').text());
$timer.stop();
$(this).parent().remove();
delete items[name];
});
<div class="-notification-box" style="top: 0px;"></div>
// внутри функции обработчика
// добавляем контейнер для таймеров в DOM если его не существует
if (!$('.timers_container').length) {
$('body').append('<div class="timers_container"></div>');
}
let Item = function(name, timer) {
this.name = name;
this.timer = timer;
}
const items = [];
if (!$('.-notification-box').length) {
$('body').append('<div class="-notification-box"></div>');
}
let $html = $(data);
$('.-notification-box').append($html);
let name = calcMD5($html.find('.inline-block.-notification-text').text());
items[name] = new Item(name, $html.find('.-notification-timer'));
items[name] = $html.find('.-notification-timer');
function startTimer(name) {
let $timer = items[name].timer;
$timer.stop();
$timer.css("width", "100%");
$timer.animate(
{width: 0},
{duration: 10000,
complete: function() {
$(this).closest('.notice__info').remove();
delete items[name];
console.log(`Удален ${name}`);
}
}
);
}
items[name] = new Item(name, $html.find('.-notification-timer'));
items[name] = $html.find('.-notification-timer');
if (items[name]) {
// повторно
startTimer(name);
} else {
// вновь
items[name] = 1;
var out = `
<div class="notice__info">
<div class="notice__info-name">
${name}
<div class="notice__timer" data-name="${name}"></div>
</div>
<div class="notice__delete">X</div>
</div>`;
$('.notice').append(out);
startTimer(name);
var Item = function(name) {
this.name = name;
}
var items = [];
$('button').on('click', function() {
if (!$('.-notification-box').length) {
$('body').append('<div class="-notification-box"></div>');
}
let $html = $(data);
let name = calcMD5($html.find('.inline-block.-notification-text').text());
items[name] = new Item(name);
if (items[name]) {
startTimer(name);
} else {
$('.-notification-box').append($html);
startTimer(name);
}
function startTimer(name) {
let $timer = items[name];
$timer.stop();
$timer.css("width", "100%");
$timer.animate(
{width: 0},
{duration: 10000,
complete: function() {
$(this).closest('.notice__info').remove();
delete items[name];
console.log(`Удален ${name}`);
}
}
);
}
});
$.ajax({
type: 'POST',
url: m_notice_click.ajax_url,
data: dataMnot,
dataType: 'json',
success: function(data) {
if (!$('.-notification-box').length) {
$('body').append('<div class="-notification-box" style="top: 0px;"></div>');
}
let $html = $(data);
let name = calcMD5($html.find('.inline-block.-notification-text').text());
items[name] = $html.find('.-notification-timer');
console.log(items[name]);
if (items[name]) {
startTimer(items[name]);
} else {
items[name] = 1;
$('.-notification-box').append($html);
startTimer($html.find('.-notification-timer'));
}
function startTimer(name) {
let $timer = name;
timer.stop();
$timer.css("width", "100%");
timer.animate({
width: 0
}, {
duration: 5000,
complete: function() {
$(this).closest(notTime).remove();
delete items[name];
}
});
}
}
});
$.ajax({
type: 'POST',
url: m_notice_click.ajax_url,
data: dataMnot,
dataType: 'json',
success: function(data) {
if (!$('.-notification-box').length) {
$('body').append('<div class="-notification-box" style="top: 0px;"></div>');
}
let $html = $(data);
let name = calcMD5($html.find('.inline-block.-notification-text').text());
if (items[name]) {
startTimer(items[name]);
} else {
items[name] = $html.find('.-notification-timer');
$('.-notification-box').append($html);
startTimer(items[name]);
}
console.log(items[name]);
function startTimer(name) {
let $timer = name;
timer.stop();
$timer.css("width", "100%");
timer.animate({
width: 0
}, {
duration: 5000,
complete: function() {
$(this).closest(notTime).remove();
delete items[name];
}
});
}
}
});