[英]add functions to javascript / JQuery object
$(".box").each(function(){
$(this).distance_left = function() {
return $(this).offset().left - $(this).parent().offset().left;
}
$(this).distance_top = function() {
return $(this).offset().top - $(this).parent().offset().top;
}
});
当我在.box对象上调用distance_left或distance_top时,我只得到一个box.distance_left is not a function
。 为什么?
您将需要扩展原型:
$.fn.distance_left = function() { return -1; };
然后可以在所有jQuery对象上使用它:
$('#myId').distance_left(); // -1
无论如何,对于您的特殊情况,您可以使用
$(this).position().left;
$(this).position().top;
因为每次创建jQuery包装器时都会返回一个新对象,所以即使将属性分配给包装器实例,该属性也不会在另一个实例中使用。
一种简单的测试方法是比较$(this) == $(this)
,该结果将返回false。
演示: 小提琴
解决方案是使用如下所示的插件模型。
$.fn.distance_left = function () {
return $(this).offset().left - $(this).parent().offset().left;
}
$.fn.distance_top = function () {
return $(this).offset().top - $(this).parent().offset().top;
}
你可以做
var that = $(this);
由于在使用新功能更改范围时, this
经常会更改,因此您不能简单地使用原始值来访问原始值。 将其别名化后that
您仍然可以访问this
的原始值。
所以你的代码是
$(".box").each(function(){
var that=$(this);
that.distance_left = function() {
return that.offset().left - that.parent().offset().left;
}
that.distance_top = function() {
return that.offset().top - that.parent().offset().top;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.