gpt4 book ai didi

javascript - 向 javascript/JQuery 对象添加函数

转载 作者:行者123 更新时间:2023-11-30 16:53:11 25 4
gpt4 key购买 nike

$(".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。为什么?

最佳答案

您将需要扩展原型(prototype):

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

然后您可以在所有 jQuery 对象上使用它:

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

无论如何,对于您的特殊情况,您可以使用

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

关于javascript - 向 javascript/JQuery 对象添加函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30187711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com