通过firefox扩展从网页中删除元素

时间:2009-05-11 08:49:07

标签: javascript html firefox xpi

我将开发一个firefox扩展,在选择文件时在文件输入字段(<input type="file">标记)旁边添加一个按钮。

文件overlay.js包含扩展程序的逻辑,通过此方法管理“文件选择”事件:

var xpitest = {
    ...
    onFileChosen: function(e) {
        var fileInput = e.explicitOriginalTarget;
        if(fileInput.type=="file"){
            var parentDiv = fileInput.parentNode;
            var newButton = top.window.content.document.createElement("input");
            newButton.setAttribute("type", "button");
            newButton.setAttribute("id", "Firefox.Now_button_id");
            newButton.setAttribute("value", "my button");
            newButton.setAttribute("name", "Firefox.Now_button_name");
            parentDiv.insertBefore(newButton, fileInput);
        }
    }
    ...
}

window.addEventListener("change", function(e) {xpitest.onFileChosen(e)},false);

我的问题是,每次我选择一个文件时,都会添加一个新按钮,请看这张图片:

http://img11.imageshack.us/img11/5844/sshotn.png

如果我多次选择同一个文件,则不会显示新按钮(这是正确的)。

正如我们所看到的,在第一个文件输入上,只选择了一个文件。

在第二个我选择了两个不同的文件,实际上已经创建了两个按钮...

第三,我选择了三个不同的文件。

正确的行为应该是:

  • 选择文件时,在输入字段旁边创建my_button
  • 如果my_button存在,请删除它并创建另一个(我需要这个,因为我应该将它连接到一个自定义事件,该事件将对文件名做一些事情)

我的问题是:如何正确删除按钮?请注意,my_button html代码不会出现在页面源上!

由于

2 个答案:

答案 0 :(得分:0)

如果我的想法太简单,请原谅我,但你不能这样做吗?

var button = document.getElementById('Firefox.Now_button_id')
button.parentNode.removeChild(button)

这是你在找什么?如果我误解了你,请随意纠正我。

答案 1 :(得分:0)

解决。我使用以下方法为每个设置了一个ID:

onPageLoad: function(e){
    var inputNodes = top.window.content.document.getElementsByTagName("input");       
    for(var i=0; i<inputNodes.length; i++){
    if(inputNodes[i].type=="file")
         inputNodes[i].setAttribute("id",i.toString());
    } 
}

我只在页面加载时调用此方法:

var appcontent = document.getElementById("appcontent");   // browser
if(appcontent)
    appcontent.addEventListener("DOMContentLoaded", xpitest.onPageLoad, true);

然后我以这种方式修改了onFileChosen方法:

onFileChosen: function(e) {
    var fileInput = e.explicitOriginalTarget;
    if(fileInput.type=="file"){
        var parentDiv = fileInput.parentNode;         
        var buttonId = fileInput.id + "Firefox.Now_button_id";
        var oldButton = top.window.content.document.getElementById(buttonId);
        if(oldButton!=null){
            parentDiv.removeChild(oldButton);
            this.count--;
        }
        var newButton = top.window.content.document.createElement("input");
        newButton.setAttribute("type", "button");      
        newButton.setAttribute("id", buttonId);
        newButton.setAttribute("value", "my button");
        newButton.setAttribute("name", "Firefox.Now_button_name");
        parentDiv.insertBefore(newButton, fileInput);
        this.count++;
    }
}
相关问题