2009-05-11 78 views
0

我打算开发一个Firefox扩展,在选择文件时在文件输入字段(<input type="file">标签)旁边添加一个按钮。通过Firefox扩展从网页中删除元素

文件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代码不会出现在页面源代码中!

谢谢

回答

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++; 
    } 
} 
0

请原谅我,如果我只是在想,但你不能这样做吗?

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

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

+0

这样可以删除所有的按钮,我需要删除相关仅与输入字段的按钮......我tryed这一点: VAR oldButton =的document.getElementById(“Firefox.Now_button_id”); (oldButton!= null)parentDiv.removeChild(oldButton); } 我想我应该使用ID,但我不能得到它的工作... – Giancarlo 2009-05-11 09:04:26

+0

这怎么能删除所有按钮?您应该只有一个带有该ID的按钮。 – 2009-05-11 09:30:17

+0

当然!但是这不会删除任何按钮,我认为是因为my_button的html代码不会出现在页面源代码中! – Giancarlo 2009-05-11 09:42:03