2017-07-30 80 views
1

已搜索答案很高而没有运气。JQuery - 使用之前声明的变量作为点击函数

我想在两个函数之间传递一个变量。第一个函数在页面加载时运行,从谷歌脚本文件中提取设置。这部分我没有任何问题。然而,我正在努力使用第二个函数,它运行'点击'并需要第一个函数的一些变量。

任何指导表示赞赏。

<script> 
    $(function() { 

     google.script.run 
      .withSuccessHandler(loadSettings) 
      .withFailureHandler(showStatus) 
      .withUserObject($('#button-bar').get()) 
      .getSettings(); 

    function loadSettings(settings) { 

    $("select").data("option",settings.userInput1); 

     }; 

    $('#add1').click(function(){ 

    var option0 = $("select").data("option");} 

    ...etc. 

    }) 

</script> 
+0

定义变量,你想要哪个变量再次使用全球 – Ritz

+0

? – Ritz

+0

@Ritz我想重复使用settings.userInput1。我试着定义一个全局变量,但是我尝试过的任何东西似乎都不起作用。 – Johnny

回答

3

我假设settings.userInput1是一个字符串。尝试下面的

<script> 
var userInput =""; 

$(function() { 

     google.script.run 
      .withSuccessHandler(loadSettings) 
      .withFailureHandler(showStatus) 
      .withUserObject($('#button-bar').get()) 
      .getSettings(); 

    function loadSettings(settings) { 
    userInput = settings.userInput1; 
    $("select").data("option",settings.userInput1); 

     }; 

    $('#add1').click(function(){ 
    //you can now use userInput in this function 
    var option0 = $("select").data("option");} 

    ...etc. 

    }) 

+0

不幸的是,这是行不通的。我只是再试一次。尽管如此,我很难过! – Johnny

+1

尝试添加console.log,并检查变量的类型' – Ritz

+1

谢谢@Ritz。非常感激。我在执行全局变量的脚本中遇到了一个错误。你的解决方案是正确的。再次感谢。 – Johnny

2

如果其他解决方案都不能正常工作,那么你应该走这条路 -

  • 做一个隐藏字段
  • 店在那个隐藏字段变量值在接下来的功能
  • 得到来自该字段的值 $("#hiddenfield_id").val();
+0

谢谢。非常有创意的做法。 – Johnny

+0

谢谢@RobertGagliano – Farsay