简体   繁体   English

为什么我的“插件”只执行一次?

[英]Why does my “plugin” execute only once?

This is my first attempt to write a jQuery plugin, this one is supposed to fade out the body, switch class, then make the body reappear and let the user switch class back. 这是我第一次编写jQuery插件,应该淡出主体,切换类,然后使主体重新出现,并让用户切换类。 Unfortunately at this point it can't switch class more than once. 不幸的是,在这一点上它不能多次切换类。 How to fix it? 如何解决?

(function($) {

    $.fn.flashClass= function(classId, element){

        element="body"; //overriden for testing purpose
            $(this).click(function() {
                $(element).fadeOut("slow", function() {
                    $(element).toggleClass(classId);
                });
                $(element).fadeIn("slow", function() {
                    $(element).scrollTop(height);
                });
            });
    };
})(jQuery);

EDIT: 编辑:

At the end of the day, It turned out that I've pasted the wrong snippet with scrollTop callback of undefined variable height . 归根结底,事实证明,我使用未定义变量height的 scrollTop回调粘贴了错误的代码段。 After removing it and switching .click to .on , function works like a charm. 取出和交换之后.click.on ,功能就像一个魅力。 However I am still interested why it worked only once. 但是我仍然很感兴趣为什么它只能运行一次。

Try the live() or on(), like following : 尝试使用live()或on(),如下所示:

 $(this).on('click',function() {...

Instead of 代替

 $(this).click(function() {...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM