简体   繁体   中英

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 . Why?

You will need to extend the prototype:

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

and then you can use it on all jQuery objects:

$('#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.

One easy way to test it is compare $(this) == $(this) which will return 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. Aliasing it to that allows you still to access the original value of 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;
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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