[英]How do we determine the HTML element (eg DIV) from where a <script></script> tag is included?
我正在編寫一個應用程序,用戶可以在其中將照片上傳到我的網站,然后通過包含類似於以下內容的腳本將此照片(以及某些其他信息)嵌入到其他任何地方:
<script src="example.com/my.js"></script>
<script>MY.embed({id: "12345"})</script>
從這個嵌入腳本中,我打算創建一個<img>
塊,並進行其他DOM操作以顯示圖像。 為了實現這一點,在MY.embed()
函數內部,我需要能夠從調用函數的位置知道DIV
或HTML
元素(或者上一個或下一個HTML元素)。
有沒有辦法做到這一點? jQuery包含在"example.com/my.js"
-因此jQuery功能可用。
大多數像這樣的javascripits都使用document.write() 。 這樣,您的腳本將寫入包含它的位置。
在將div放置在某處之后,您可以通過其ID在DOM中找到它。
var scripts = document.getElementsByTagName('script');
for (var index = 0; index < scripts.length; index++) {
var script = scripts[index];
if (script.src.indexOf("my.js") != -1) {
//found the script, do what you want with the parent node here
alert(script.parentNode.id);
}
}
我認為,但我尚未測試過,由於javascript是在解析文檔時運行的,因此dom中最后一個腳本標簽是您內部的腳本標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.