2011-11-05 113 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