我试图实现通知风格的JQuery函数。这是我到目前为止所拥有的
function notify(message, type, autohide, delay) {
message = message;
type = type || "";
autohide = autohide || false;
delay = delay || 0;
$('#notification-container').append("<div class='notice " + type + "'>" + message + "<div class='close-container'><span class='glyphicon glyphicon-remove'></span></div></div>");
};
调用此功能会正确添加通知,但在“延迟”之后我还无法删除该特定元素。一段时间没有删除所有其他通知。我搜索但只找到基于#id的解决方案或基于类。我不想在每个新通知上放置ID,如果我通过.notice删除它,所有通知都会同时到期。我最接近的是使用
if (autohide) {
setTimeout(function () {
$('#notification-container .notice:last-child').remove();
}, delay);
}
但我相信你们所有人都能看出这有什么不妥之处。任何帮助或建议将不胜感激。
答案 0 :(得分:1)
您可以尝试这样的事情:
var deleteNotice = function(elem,delay){
var tout = setTimeout(function(){
clearTimeout(tout);
elem.remove()
},delay);//Now this acts on only this element
}
function notify(message, type) {
$('#notification-container').append("<div class='notice " + type + "'>" + message + "<div class='close-container'><span class='glyphicon glyphicon-remove'></span></div></div>");
//Now assign this element to a variable, so everytime your function is called el represents the latest notice
var el = $('#notification-container .notice:last-child');
deleteNotice(el,10000);//A function to delete this selected element
};
答案 1 :(得分:1)
您可以将元素设为jQuery对象并使用该引用将其删除
function notify(message, type, autohide, delay) {
message = message;
type = type || "";
autohide = autohide || false;
delay = delay || 0;
var $notification = $("<div class='notice " + type + "'>" + message + "<div class='close-container'><span class='glyphicon glyphicon-remove'></span></div></div>");
$('#notification-container').append($notification);
if (autohide) {
setTimeout(function() {
$notification.remove();
}, delay);
}
}
答案 2 :(得分:0)
我会创建元素并将它们存储在局部变量中,这样只会删除该函数调用的元素。像
这样的东西function notify(message, type, autohide, delay) {
var div = $('<div />', {
'class' : 'notice' + (type ? ' '+type : ''),
text : message || ''
}),
close = $('<div />', {
'class' : 'close-container',
on : {
click : function() {
div.remove();
}
},
html : $('<span />', {
'class' : 'glyphicon glyphicon-remove'
})
});
if (autohide) {
div.delay(delay||0).hide(0, function() {
$(this).remove();
});
}
$('#notification-container').append(div.append(close));
}