问题
我刚刚开始学习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); };
问题
为什么原始版本使用
返回这个.each
而不是return $(this).each
?- 注意:我无法在我的版本上使用
this
,否则会返回错误:Uncaught TypeError: Object [object global] has no method 'each'
- 注意:我无法在我的版本上使用
each
不是一个 jQuery 方法吗?- 据我了解,使用
this
时,您可以对其调用 DOM 方法,但不能调用 jQuery 方法。反之亦然。
- 据我了解,使用
为什么我的版本不起作用?我缺少什么?
- 注意:我没有错误,因此调试起来比较困难。
最佳答案
- 在插件对象内
this
指的是启动插件的 jQuery 包装器对象,而不是其他方法中的 dom 对象 - 由于
this
是 jQuery 包装对象.each()
可用 - 您的实现中存在多个问题
- 当您调用
call_a_or_b
时,您没有将执行上下文传递给该方法,因此方法中的this
引用了window
对象 - 根据经验,要在 jQuery 中启用链接,您需要返回 jQuery 包装器,但您没有这样做
- 替代方法存在关闭和调用相关问题
- 当您调用
尝试
(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/