【问题标题】:problem with variable (firefox extension)变量问题(firefox扩展)
【发布时间】:2009-08-20 15:25:01
【问题描述】:

我尝试制作 Firefox 扩展,显示两个按钮:1 和 2。当您按下按钮 1 以 var path 获取值时,即当前打开页面的地址,然后新标签打开变为活动状态。在此选项卡中有 button2,它允许放置 var 路径的(innerHTML)值(第一个选项卡的此地址)。 现在的问题是:button1 使用函数 kuku.open() 和 button2 使用 kuku.save(),但是第一个函数中的 var 在 kuku.save() 中不存在

var kuku = {

open: function () {
//put current URI addres into var
var path=content.location.href;

//Create nslFile object
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath(path);

//Put file content into data variable
var data = "";
var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
                        createInstance(Components.interfaces.nsIFileInputStream);
var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
                        createInstance(Components.interfaces.nsIConverterInputStream);
fstream.init(file, -1, 0, 0);
cstream.init(fstream, "UTF-8", 0, 0); // you can use another encoding here if you wish

let (str = {}) {
  cstream.readString(-1, str); // read the whole file and put it in str.value
  data = str.value;
}
cstream.close(); // this closes fstream

//Open editor in new Tab and select it

var tab=gBrowser.addTab("http://www.google.pl");
var newTabBrowser = gBrowser.getBrowserForTab(tab);
gBrowser.selectedTab=tab;

},


save: function () {
//Write in body address from var
content.body.innerHTML=path;
}
}

我认为,问题是因为路径是本地变量,但我不能使用全局变量。它可以工作,每个浏览器只有一个标签。我的意思是,当用户按下页面 A 上的 button1 和页面 B 上的 button1 时,这两个新打开的页面将具有相同值的 var 路径。当您按下其他站点上的按钮时,它将覆盖路径的值。我希望,我没有让你感到头晕;)

有人知道了吗?

【问题讨论】:

    标签: javascript variables


    【解决方案1】:

    将变量放在对象中,而不是函数中。如果变量在函数中,那么只有函数可以访问它:

    var kuku = {};
    kuku.path = "";
    
    kuku.open = function () {
      kuku.path = content.location.href;
      //The rest of the code here
    };
    
    
    kuku.save = function () {
      content.body.innerHTML=kuku.path;
    };
    

    【讨论】:

    • 它不起作用:(当我打开 2 个选项卡(例如 google.com 和 facebook.com)并从 gogle 中按下按钮 1 时,它将打开新选项卡和 kuku.path 的值将是 google 地址。但是接下来,当我在 facebook 中按 button1 时,值将更改为 facebook 地址,并且在这两个新打开的页面中将是相同的
    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多