gpt4 book ai didi

javascript - 为什么我的 Jquery 方法切换替代方案不起作用?

转载 作者:行者123 更新时间:2023-11-28 08:52:48 24 4
gpt4 key购买 nike

问题

我刚刚开始学习javascript。我正在尝试以更模块化的方式重现一段工作代码。它帮助我保持事情干净,并更好地理解它。

我确信有更有效或更简洁的方法来实现代码的功能,所以请女士们/男士们不要提及它——您可以省点力气。这里的重点是通过玩代码来学习我还不理解的东西。

代码的作用

它创建了方法 toggle that has been deprecated 的替代方法然后可以按以下方式使用 $('#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. 为什么原始版本使用返回这个.each而不是 return $(this).each?

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

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

    • 注意:我没有错误,因此调试起来比较困难。

最佳答案

  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);

演示:Fiddle

关于javascript - 为什么我的 Jquery 方法切换替代方案不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com