2011-11-05 56 views
0

我想改變我的動態創建的div ,但我不能得到這個工作 它不斷創造新的div一個發現動態創建的div

var div = document.getElementById('windowx'); 
var btn; 
var doc = content.document 

if (div) 
{ 
    div = document.getElementById('windowx') 
    div.innerHTML = "something new" 
} 
else 
{ 
    doc = content.document 
    div = doc.body.appendChild(doc.createElement("div")) 
    div.setAttribute("id", "windowx") 
    div.setAttribute("style", 
    "position: fixed; top: 100px; left: 100px; width: 20em;" 
    + "border: 2px outset orange; background-color: cornsilk;" 
    ) 
    btn = div.appendChild(doc.createElement("button")) 
    btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;") 
    btn.setAttribute("onclick", "document.body.removeChild(this.parentNode)") 
    btn.appendChild(doc.createTextNode("Zamknij")) 
} 
+1

嘗試'var div = content.document.getElementById('windowx');'。爲什麼用相同的值多次初始化變量? –

+1

你對分號過敏嗎? – tvanfosson

+0

是否適用於Firefox插件? –

回答

2

現在,很顯然這是一個Firefox插件:

document.getElementById將在瀏覽器的用戶界面,元搜索,而不是網頁。但是稍後您將該元素添加到頁面中。因此,你必須在網頁中搜索該元素:

var div = content.document.getElementById('windowx'); 

而且,你在做一些不必要的方法調用。以下是您的代碼的更清晰版本:

var doc = content.document, 
    div = doc.getElementById('windowx'), 
    btn; 

if (div) { 
    div.innerHTML = "something new" 
} 
else { 
    div = doc.body.appendChild(doc.createElement("div")) 
    div.setAttribute("id", "windowx") 
    div.setAttribute("style", 
    "position: fixed; top: 100px; left: 100px; width: 20em;" 
    + "border: 2px outset orange; background-color: cornsilk;" 
    ) 
    btn = div.appendChild(doc.createElement("button")) 
    btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;") 
    btn.setAttribute("onclick", "document.body.removeChild(this.parentNode)") 
    btn.appendChild(doc.createTextNode("Zamknij")) 
} 
+0

我有另一個簡單的問題; p有一個簡單的方法來創建光標位置的div?我的意思是像div.setAttribute(「樣式」, 「position:fixed; top:mouseX; left:mouseY; width:20em;」 +「border:2px outset orange; background-color:cornsilk;」 ) ? – user1031241

+0

我想這個位置應該是絕對的,如果你有座標,你可以這樣做...... –

0

對我來說是窒息content.document,window對象沒有按」沒有內容屬性,所以我不確定你在引用什麼。清理了一下,它似乎工作。注意我直接添加click處理程序,而不是將其設置爲屬性。看到這裏,我有它觸發了一個jQuery按鈕單擊處理程序:http://jsfiddle.net/hN8uz/1/

var doc = document; 
var div = doc.getElementById('windowx'); 
var btn; 

if (div) { 
    div.innerHTML = "something new"; 
} 
else { 
    div = doc.body.appendChild(doc.createElement("div")); 
    div.setAttribute("id", "windowx"); 
    div.setAttribute("style", "position: fixed; top: 100px; left: 100px; width: 20em;" + "border: 2px outset orange; background-color: cornsilk;"); 
    btn = div.appendChild(doc.createElement("button")); 
    btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;"); 
    btn.onclick = function() { 
     document.body.removeChild(this.parentNode); 
    }; 
    btn.appendChild(doc.createTextNode("Zamknij")); 
} 
+0

這可能是在Firefox插件的上下文中......至少這就是我所設想的。 –

+0

我想它可能在FF中工作,但我使用Safari。沒有在FF中試用它,也不清楚OP是否使用FF。 – tvanfosson