也许我的大脑被炸了,但我正在编写一个插件,它创建了一个元素的调整,但也创建了一个我想访问的对象。所以插件看起来像这样
(function ($) {
$.fn.myPlugin = function () {
return this.each(function () {
// do some stuff to the element...
this.objectInstance = new usefulObject();
});
};
})(jQuery);
function usefulObject(){
// useful object properties and methods....
this.doSomething = function(){
alert("Don't google Google. You'll break the internet.");
}
}
所以当我调用插件时,我还希望能够访问我创建的那个有用的对象。我认为这样的事情可能会奏效....
tweakedElement = $("#someDiv").myPlugin();
tweakedElement.objectInstance.doSomething();
...但这不起作用。我怎样才能做到这一点?我能做到吗?明信片上或下面的答案,以适合您的方式为准。
最佳答案
您可以使用 jQuery 的 data
函数将 objectInstance
存储在相关元素上:
http://api.jquery.com/jQuery.data/
The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can set several distinct values for a single element and retrieve them later
关于javascript - 我可以获得对在 jQuery 插件中创建的对象的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783889/