2011-06-07 18 views
2

我想在創建元素的<script>元素之後追加元素。它爲http://guubo.com/多分享服務,因此代碼的目的是創建IFRAME元素按鈕。document.body.appendChild在包含JS的地方

guubo   = new Object(); 

// create iframe 
guubo.iframe = document.createElement('iframe'); 

guubo.iframe.setAttribute('style', 'border:none; overflow:hidden; width: 93px; height: 32px;'); 
guubo.iframe.setAttribute('scrolling', 'no'); 
guubo.iframe.setAttribute('frameborder', '0'); 
guubo.iframe.setAttribute('allowTransparency', 'true'); 

document.body.appendChild(guubo.iframe); 

如何運行此代碼<script>guubo.iframe元素追加?請注意,頁面上可能會有多個<script>,並且具有相同的URL,因此搜索具有相同URL的腳本元素並在其不是選項之後追加。

+0

那麼問題是什麼? – lonesomeday 2011-06-07 11:36:07

+0

那麼該怎麼做? – Gajus 2011-06-07 11:36:34

+0

你怎麼做? – circusbred 2011-06-07 11:38:16

回答

0

如果你的意思是要包含代碼的script元素之後插入一個iframe,我覺得不過這個選擇至今處理[瀏覽器/ DOM引擎]的最後一個腳本元素,之後追加會做的伎倆,可能並不總能產生預期的效果,因爲不同瀏覽器加載頁面中的資源的方式不同。

此外,您可以使用var guubo = {};而不是guubo = new Object();

+0

如何獲得最後處理的'script'元素? – Gajus 2011-06-07 12:12:26

+0

'var els = document.getElementsByTagName('script'); els [els.length-1];'但是你會更好地使用[inti](http://stackoverflow.com/questions/6264570/document-body-appendchild-in-place-where-the-js-is -included/6264749#6264749)的解決方案。 – 2011-06-07 12:19:03

0

要做到這一點,有一箇舊的髒方法來使用document.write()來放置腳本所在的html代碼。但是如果你想以另一種方式做到這一點,你需要在文檔中提供一個參考點。通常是這樣的:

<div id="guubo_btn"></div> 
<script> 
    /* Your script */ 
    document.getElemenytById("guubo_btn").appendChild(guubo.iframe); 
</script> 

這會把它放在scipt標籤之前,但結果是一樣的。

編輯:執行document.write()方法,只用了iframe

var guubo = {}; 

guubo.iframe_id = "ifr"+Math.floor(Math.random()*1000); 

// create iframe 
var iframe = '<iframe '; 
iframe += 'style="border:none; overflow:hidden; width: 93px; height: 32px;" '; 
ifarme += 'id="'+guubo.iframe_id+'" '; 
iframe += 'scrolling="no" '; 
iframe += 'frameborder="0" '; 
iframe += 'allowTransparency="true"></iframe>'; 
document.write(iframe); 

guubo.iframe = document.getElementById(guubo.iframe_id); 

編輯2:現在你有guubo對象的iframe。

+0

所以這樣的事情? http://pastebin.com/0zKWDeN1 – Gajus 2011-06-07 12:29:47

+0

那麼...第1如果你使用document.write()你可以寫iframe,不需要div。第二,不要在div中使用document.write(),只需在HTML中添加一個div上方的腳本標籤。但是,是的,你的解決方案可能工作。 – aorcsik 2011-06-07 12:48:20

+0

如果我只是'ducument.write(guubo.iframe)'我得到'[object HTMLIFrameElement]'。有什麼我失蹤? – Gajus 2011-06-07 13:05:32