我正在尝试实现通知样式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,如果我通过 .notification 将其删除,所有通知将同时过期。我最接近使用的
if (autohide) {
setTimeout(function () {
$('#notification-container .notice:last-child').remove();
}, delay);
}
但我相信你们所有人都能看到这是有缺陷的。任何帮助或建议将不胜感激。
您可以将该元素设为 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);
}
}
你可以尝试这样的事情:
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
};
我会创建元素并将它们存储在局部变量中,这样只会删除该函数调用的元素。类似的东西
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));
}
小提琴
这是一个支持动画的版本