简体   繁体   English

向javascript / JQuery对象添加功能

[英]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;
    }

});

When I call distance_left or distance_top on a .box object, I simply get a box.distance_left is not a function . 当我在.box对象上调用distance_left或distance_top时,我只得到一个box.distance_left is not a function Why? 为什么?

You will need to extend the prototype: 您将需要扩展原型:

$.fn.distance_left = function() { return -1; };

and then you can use it on all jQuery objects: 然后可以在所有jQuery对象上使用它:

$('#myId').distance_left(); // -1

Anyway for your particually case you can use 无论如何,对于您的特殊情况,您可以使用

$(this).position().left;
$(this).position().top;

Because each time you create a jQuery wrapper a new object is returned, so even though you assign the properties to a wrapper instance it won't be available in another one. 因为每次创建jQuery包装器时都会返回一个新对象,所以即使将属性分配给包装器实例,该属性也不会在另一个实例中使用。

One easy way to test it is compare $(this) == $(this) which will return false. 一种简单的测试方法是比较$(this) == $(this) ,该结果将返回false。

Demo: Fiddle 演示: 小提琴

The solution here is to use a plugin model as given below. 解决方案是使用如下所示的插件模型。

$.fn.distance_left = function () {
    return $(this).offset().left - $(this).parent().offset().left;
}
$.fn.distance_top = function () {
    return $(this).offset().top - $(this).parent().offset().top;
}

You could do 你可以做

var that = $(this);

Because this frequently changes when changing scope by using a new function, you cannot simply access the original value by using it. 由于在使用新功能更改范围时, this经常会更改,因此您不能简单地使用原始值来访问原始值。 Aliasing it to that allows you still to access the original value of this . 将其别名化后that您仍然可以访问this的原始值。

So your code would be 所以你的代码是

$(".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.

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