gpt4 book ai didi

javascript - 向一个 jQuery/DOM 元素添加一个函数

转载 作者:行者123 更新时间:2023-12-02 19:28:32 24 4
gpt4 key购买 nike

我正在编写一个实例化 map 的插件。然后 map 将提供移动到地球上另一个地方的功能。

该脚本使 map 效果很好。但是,我无法“固定”元素上的函数,以供回调中的另一个插件使用。

这是我尝试过的方法;在插件中:

(function($){
$.fn.mapDo(options){
map = new BlahMap(this.get(0));

this.moveTheMap = function(place){
map.moveItToThat(place);
}; // nope.
}
})(jQuery);

然后,在 View 中:

$(map).mapDo();

$(otherElement).otherControl({
callback: function(place){
$(map).moveTheMap(place); // moveTheMap is not there on $(map)!
}
};

问题

如果可能的话,如何向 map jQuery 或 DOM 元素添加函数?如果没有,我怎样才能提供这种功能?

更重要的是,我通过这种方式分离事物的方式是否正确?我对 Javascript 有点陌生,通常如何在保持组件分开的情况下完成这些任务?

虽然这是我所做的尝试,但更一般地说,我在保持可链接性的同时从 jQuery 插件输出内容的概念上遇到了困难。在这种情况下,我想做的是输出来自插件的回调,该回调将在稍后的执行中处理被调用的元素。

最佳答案

插件通常只向 jQuery 原型(prototype)添加一种方法,并且对插件实例的方法调用是通过字符串完成的。

(function($) {
$.fn.mapDo = function(options) {
var args = [].slice.call(arguments, 1); //Get all the arguments starting from 2nd argument as an array
return this.each(function() {
var $this = $(this),
instance = $this.data("map-instance");
if (!instance) {
$this.data("map-instance", (instance = new BlahMap(this, options)));
}
if (typeof options == "string") {
instance[options].apply(instance, args);
}
});
};
})(jQuery);

$(elem).mapDo( "moveTheMap", place ); //This would also instantiate the plugin if it wasn't instantiated

这是 jsfiddle 展示它的实际效果:

http://jsfiddle.net/X8YA8/1/

关于javascript - 向一个 jQuery/DOM 元素添加一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774204/

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