繁体   English   中英

为什么我在Jquery中切换方法的替代方法不起作用?

[英]why is that my alternative to the method toggle in Jquery not working?

问题

我刚刚开始学习JavaScript。 我试图以一种更加模块化的方式重现一段有效的代码。 它可以帮助我保持事物清洁,并更好地理解它。

我敢肯定,有更好的效率或简洁的方法可以实现代码的功能,因此请女士们/女士们不要提及它-您可以在此上节省您的呼吸。 这里的重点是通过玩代码来学习我尚不了解的东西。

该代码做什么

它创建了已过时的方法切换的替代方法,然后可以按以下方式使用$('#foo h2').mytoggle(plus,minus);

以下是原始代码:

$.fn.clicktoggle = function(a, b) {
return this.each(function() {
    var clicked = false;
    $(this).click(function() {
        if (clicked) {
            clicked = false;
            return b.apply(this, arguments);
        }
        clicked = true;
        return a.apply(this, arguments);
    });
});
};

以下是我之前的代码版本:

function call_a_or_b (a,b) {
    var clicked = false;
    function alternate (a,b) {
        if (clicked) {
        clicked = false;
        return a.apply(this, arguments);
        }
        else {
        clicked = true; 
        return b.apply(this, arguments);
        }
    } // end function alternate


    return $(this).each(function () {$(this).click(alternate(a,b))}); 
} //end function call_a_or_b

$.fn.clicktoggle = function(a,b) {  call_a_or_b(a,b); };

问题

  1. 为什么原始版本使用return this.each而不是return $(this).each

    • 注意:我不能在我的版本上使用this ,否则它将返回错误: Uncaught TypeError: Object [object global] has no method 'each'
  2. each不是jQuery方法吗?

    • 据我了解,使用this方法时,可以在其上调用DOM方法,但不能调用jQuery方法。 反之亦然。
  3. 为什么我的版本不起作用? 我想念什么?

    • 注意:我没有任何错误,因此很难调试。

当您将函数分配给$.fn它将在jQuery上下文中执行,因此this是一个jQuery对象。 您的函数最有可能在窗口的上下文中执行。 如果将最后一行更改为this,则它应该完全相同:

$.fn.clicktoggle = call_a_or_b(a,b);
  1. 在插件对象内部, this是指在其上启动插件的jQuery包装器对象,而不是其他方法中的dom对象。
  2. 由于this是jQuery包装器对象,因此.each()可用
  3. 您的实施中存在多个问题
    1. 当您调用call_a_or_b您没有将执行上下文传递给该方法,因此this方法内部的该对象是指window对象
    2. 根据经验,要在jQuery中启用链接,您需要返回未使用的jQuery包装器
    3. 替代方法存在与关闭和开发相关的问题

尝试

(function ($) {
    function call_a_or_b(a, b) {

        //for each matched element the clicked variable should be a closure one, so needed to rearrage it a bit        
        function alternate(el) {
            var clicked = true;
            $(this).click(function () {
                if (clicked) {
                    clicked = false;
                    return a.apply(this, arguments);
                } else {
                    clicked = true;
                    return b.apply(this, arguments);
                }
            })
        } // end function alternate

        return $(this).each(alternate);
    } //end function call_a_or_b

    $.fn.clicktoggle = function (a, b) {
        //call the method with the current execution context and return the value returned fromit
        return call_a_or_b.apply(this, arguments);
    };
})(jQuery);

演示: 小提琴

暂无
暂无

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

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