寻找动态创建的div

时间:2011-11-05 15:56:21

标签: javascript dom firefox-addon

我想改变我动态创建的div 但我不能让这个工作 它不断创造新的divs

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"))
}

2 个答案:

答案 0 :(得分:2)

现在很明显它适用于Firefox插件:

document.getElementById将在浏览器UI中搜索该元素,而不是网页。但是稍后您要将该元素添加到页面中。因此,您必须在页面中搜索该元素:

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"))
}

答案 1 :(得分:0)

对我来说,它在content.document上窒息,窗口对象没有内容属性,所以我不确定你在引用什么。清理了一下,它似乎工作。注意我直接添加了单击处理程序,而不是将其设置为属性。看到这里我用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"));
}