使用JQuery 5秒后隐藏元素的实例
我试图实现通知样式JQuery函数。这里是我到目前为止使用JQuery 5秒后隐藏元素的实例
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);
}
但我敢肯定,你们都可以看到这是如何有缺陷。任何帮助或建议,将不胜感激。
可以使元素的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);
}
}
哇,我真的这个答案,虽然我不知道它是如何工作的。当你说$ notification.remove()时,jquery如何知道我正在谈论哪个$通知? – WiseOlMan
而不是附加一个匿名html字符串,该字符串被转换为dom元素..你正在附加一个由jQuery对象表示的dom元素。对象的引用在追加过程中不会丢失 – charlietfl
至于知道哪个...函数调用的每个实例中只有一个范围变量对象 – charlietfl
你可以尝试这样的事:
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));
}
东西
我看不出有什么错在你的代码。你在控制台中看到任何错误吗?如果您的主代码中有可用的声明,那么在哪里? –
http://*.com/questions/3655627/jquery-append-object-remove-it-with-delay –
@ÁlvaroTouzón我已经看到了这个问题,但它基于类去除它。 – WiseOlMan