代码之家  ›  专栏  ›  技术社区  ›  Ben

重复JS函数的最佳方法

  •  0
  • Ben  · 技术社区  · 14 年前

    有时调用这个函数太快,会创建多个元素,但由于它使用的ID不是每个实例的唯一ID,因此淡出并删除div的部分只适用于顶级元素,而不是所有元素。所以我最终得到了一个静态div标签,它不会褪色/移除。

    我能想到的最好的办法就是再重复一遍。我该怎么做,还是有更好的方法?

    document.triggerNotification = function (type, message) {
        jQuery(document.body).append("<div class='push-notification push-"+type+"' id='notification'>"+message+"</div>");
    
        jQuery('#notification').delay(1500).fadeOut(1200, function () {
            jQuery('#notification').remove();
        });
    }
    
    4 回复  |  直到 14 年前
        1
  •  3
  •   mikerobi    14 年前

    function (type, message) {
        var el = $("<div class='push-notification push-"+type+"'>"+message+"</div>");
        jQuery(document.body).append(el);
    
        el.delay(1500).fadeOut(1200, function () {
           el.remove();
        });
    }
    
        2
  •  0
  •   spender    14 年前

    给他们唯一的身份证怎么样?

    var notificationCount=0;
    document.triggerNotification = function (type, message) {
        notificationCount++;
        var notificationId="notification"+notificationCount;
        jQuery(document.body).append("<div class='push-notification push-"+type+"' id='"+notificationId+"'>"+message+"</div>");
    
        jQuery('#'+notificationId).delay(1500).fadeOut(1200, function () {
            jQuery('#'+notificationId).remove();
        });
    }
    
        3
  •  0
  •   LVB    14 年前

    1. 通过添加一个不断增加的数字(例如),使您的ID唯一。
    2. 使用一个新类作为您感兴趣的行的指示符,然后使用“.notificationID”样式选择器附加淡出。
        4
  •  0
  •   Ender    14 年前

    与使用ID作为句柄来设置/删除通知的动画不同,您可以简单地将其创建为函数调用中的变量,从而提供删除通知的方法。像这样:

    document.triggerNotification = function(type, message) {
        var notification = $("<div class='push-notification push-" + type + "'>" + message + "</div>");
        jQuery(document.body).append(notification);
    
        setTimeout(function() {
            notification.fadeOut(1200, function() {
                notification.remove();
            })
        }, 1500);
    };
    

    另外,我认为在这种情况下 setTimeout .delay() . 虽然他们都能工作, .延迟() 在这种情况下就足够了,因为您只调用一个动画。请参阅此处的文档: http://api.jquery.com/delay/

    最后,这里是我提供的代码的工作演示: http://jsfiddle.net/WqwsN/