![](/img/trans.png)
[英]Use of jquery noconflict function when including external js libraries and js code files
[英]How can I use libraries in external js files?
我試圖將我的對象寫在一個單獨的js文件中,以使我的主要HTML文件更易於組織。 當我使用jquery或oCanvas(畫布庫)語法時,它似乎無法識別並且無法執行。 我希望能夠為我的主體創建對象模板,以從中創建克隆(使用oCanvas中的clone()函數)。
主HTML
<script language="javascript" type="text/javascript">
var canvas = oCanvas.create({
canvas: "#myCanvas",
background: "#CCCCCC"
});
helloworld();
</script>
外部JS文件
var rectangle = canvas.display.rectangle({
x: 77,
y: 77,
width: 200,
height: 100,
fill: "#0aa"
});
function helloworld(){
alert(rectangle.x);
};
當我調用對象rectangle
並警告它的x屬性時,它會失敗。 這與使對象成為全局對象有關嗎?
由於helloworld
位於封閉中,因此您需要將其導出到外部作用域以在其他地方使用它:
$(document).ready(function(){
var rectangle = canvas.display.rectangle({
x: 77,
y: 77,
width: 200,
height: 100,
fill: "#0aa"
});
function helloworld(){
alert(rectangle.x);
};
window.helloworld = helloworld; // make it global
});
但是,您粘貼的腳本會立即調用該函數,直到該腳本運行后才會對其進行定義。 因此,您必須等到DOM加載后才能調用helloworld()
。
刪除$(document).ready(function(){
和});
以來:
helloworld
不是全局的,因此您無法從其他腳本元素訪問它, 並且 helloworld
之后), rectangle
才會被賦值。 編輯問題后
這是您的代碼執行順序:
rectangle
helloworld
嘗試從rectangle
讀取值 您必須先創建畫布,然后再嘗試從中讀取數據。
方式之一:
您應該觸發自定義事件:
$(document).ready(function(){
...
window.hello = function(name){alert('Hello, '+name+'!');}
// document.dispatchEvent(new CustomEvent('libLoaded', { name: 'hello' }));
document.dispatchEvent(new CustomEvent('libLoaded_hello', {}));
...
});
然后等待:
document.addEventListener('libLoaded_hello', function(e){
// console.log(e.name);
hello('World');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.