代码之家  ›  专栏  ›  技术社区  ›  FabricioG

无法在从另一个函数调用变量的函数中设置变量

  •  0
  • FabricioG  · 技术社区  · 6 年前

    我目前正在运行一个节点JS文件,我正在收到这样的帖子。

    app.post('/', function (req, res) {
        var firstLine = req.body.firstLine;
        var secondLine = req.body.secondLine;
        var previewID = req.body.previewId;
        takeWebshot(firstLine)
        return res.end('<h1>Hello, Secure City World!</h1>');
    });
    

    当我console.log firstline设置为req.body.firstline时,让我们说它是“hello”。所以firstline=“你好”。 然后我把这个变量传递给 takeWebshot(firstLine) . 当我在Takewebshot中控制LogFline时,我可以看到“你好”。

        function takeWebshot(fLine) {
    console.log(fLine);
            var options = {
              onLoadFinished: {
                fn: function() {
                  document.getElementById("user_input").value=fLine;
                  document.getElementById("second_user_input").value="AMAZON USERNAME";
                  document.getElementById("preview_btn").click();
                }
              },
              takeShotOnCallback: true,
              captureSelector: '.fancybox-outer'
            };
    
            webshot('example.com/testy.html', './example.png', options, function(err) {
              if (err) return console.log(err);
              console.log('OK');
            });
          };
    

    这是我的问题:

    document.getElementById("user_input").value=fLine;
    

    弗林特不再读了。我试着把燧石传递到这里的函数中,就像这样。弗林现在等于“成功”。在我对JS有限的了解中,函数fn:function()似乎是主节点模块webshot中的Promise回调。目标是我需要

    document.getElementById("user_input").value=fLine; to equal firstLine that is being sent by the other function.
    

    编辑:webshot正在调用一个幻影JS来打开一个url headless。我正在尝试传递变量,以便它在调用窗体进行屏幕截图时能够填写该窗体。这就是为什么它有文档。

    2 回复  |  直到 6 年前
        1
  •  1
  •   customcommander    6 年前

    文件 webshot 提到在传递给幻影之前脚本将被序列化

    请注意,脚本将被序列化,然后作为文本传递给幻影,因此所有变量范围信息都将丢失。但是,调用方的变量可以按如下方式传递到脚本中:

    囊性纤维变性 https://www.npmjs.com/package/webshot#phantom-callbacks

    所以你应该按照他们的指示做一些类似的事情:

    onLoadFinished: {
      fn: function() {
        document.getElementById("user_input").value=this.fLineSnapshot;
        document.getElementById("second_user_input").value="AMAZON USERNAME";
        document.getElementById("preview_btn").click();
      },
      context: {
        fLineSnapshot: fLine
      }
    },
    
        2
  •  0
  •   Arulmozhi Manikandan    6 年前

    你不能通过弗林特 fn: function(fLine) 因为它是OnLoadFinished的回调函数,所以变量的范围在内部不可访问,您可以尝试 fn: () => { document.getElementById("user_input").value=fLine; } 这可以作为fat arrow函数使用,允许访问使用变量outside函数。