如何在JavaScript onclick函数中运行jQuery代码?
单击“关闭” anchor
不会关闭通知。
以下是我的代码:
function show_notification_on_top(message, type) { content = "close"+ ""+message+"
"; $("#notification-box").fadeIn('slow', function() { $("#notification-box").delay(60000).fadeOut('slow'); }); $("#notification-box").html( content ); }
不要在链接上硬编码
onclick
事件,使用JQuery click
unobtrusive subscriber。
function show_notification_on_top(message, type) { content = "close"+ " message
"; $("#notification-box").fadeIn('slow', function() { $("#notification-box").delay(60000).fadeOut('slow'); }); $("#notification-box").html( content ); $('.notify-close').click(function(){ $('#notification-box').dequeue(); }); }
没试过代码,但你想要这样的东西……
function show_notification_on_top(message, type) { var anc = $('').addClass('notify-close').html('close').click(function() {$('#notification-box').fadeOut(); }); $("#notification-box").append( anc ).fadeIn('slow', function() { $("#notification-box").delay(60000).fadeOut('slow'); }); }
事实上,这是行不通的。 几件事。
首先:将click事件添加到代码中,而不是添加到标记中。 这可以真正简化函数中的代码。
第二:由于之前的延迟和fadeOut到位,您的动画尝试(fadeOut)将失败。 要正确地工作,只需将您拥有的那个出列。
function show_notification_on_top(message, type) { content = "close" + "" + message + "
"; $("#notification-box").fadeIn('slow').delay(60000).fadeOut('slow'); $("#notification-box").html(content); } $(document).on('click', '.notify-close', function() { $('#notification-box').dequeue(); });
请注意.on('click',
添加一个实时事件处理程序,允许您从标记中删除事件。
我编写的代码是什么:显示关闭的消息可以激活,如果没有手动关闭,则等待60000毫秒,然后按照定义淡出。
这是一个工作示例: http : //jsfiddle.net/MarkSchultheiss/X6qDJ/
编辑:OP的注意事项。 如果您已经确定必须立即包含该事件,则可以将代码更改为:
content = "close" + "" + message + "
";
代替:
content = "close" + ""+message+"
";
谢谢大家。 在你的帮助下,我写了这段代码。 工作得很好。
function show_notification_on_top(message) { content = "close_button_label"+ ""+message+"
"; $("#notification-box").fadeIn('slow'); $("#notification-box").html( content ); $('#notification_anchor').click(function() { $("#notification-box").fadeOut("slow"); }); window.setTimeout(function() { $("#notification-box").fadeOut('slow'); }, 6000); }
添加这个:
$(document).ready(function(){ $(".notify-close").live("click", function(){ $("#notification-box").fadeOut('slow'); }); });
并忘记onclick()事件;