[英]How can I access an instance object from other script?
我有兩個腳本: scipt1.js:
(function ($) {
'use strict';
var A = function (element, options) {
this.element = $(element);
};
A.prototype.update = function update() {}
$.fn.doA = function (option) {
return this.each(function test() {
newA = new A(this, options);
}
});
};
}(jQuery));
和來自斜坡html的 scipt2.js:
$( document ).ready(function(){
$('#$this->id').doA($javascriptParameterString);
});
在 $( document ).ready(function().. from script2.js 中,我想在執行 doA 后從 scipt1.js 調用 function 更新。無論如何我可以引用實例 newA 並調用 function 更新嗎?
使用.data
將調用doA
的元素與實例相關聯,然后.data
可以在其他地方使用來檢索它。
var A = function(element, options) { this.element = $(element); this.options = options; }; $.fn.doA = function(options) { return this.each(function test() { $(this).data('a', new A(this, options)); }); }; // Other script: $(document).ready(function() { $('.foo').doA({ property: 'foo' }); console.log('now iterating over instantiated As:'); for (const foo of $('.foo')) { const a = $(foo).data('a'); console.log(a.options); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="foo"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.