[英]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); };
为什么原始版本使用return this.each
而不是return $(this).each
?
this
,否则它将返回错误: Uncaught TypeError: Object [object global] has no method 'each'
each
不是jQuery方法吗?
this
方法时,可以在其上调用DOM方法,但不能调用jQuery方法。 反之亦然。 为什么我的版本不起作用? 我想念什么?
当您将函数分配给$.fn
它将在jQuery上下文中执行,因此this
是一个jQuery对象。 您的函数最有可能在窗口的上下文中执行。 如果将最后一行更改为this,则它应该完全相同:
$.fn.clicktoggle = call_a_or_b(a,b);
this
是指在其上启动插件的jQuery包装器对象,而不是其他方法中的dom对象。 this
是jQuery包装器对象,因此.each()
可用 call_a_or_b
您没有将执行上下文传递给该方法,因此this
方法内部的该对象是指window
对象 尝试
(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.