【问题标题】:Can't call script from script with JQuery in GAS无法在 GAS 中使用 JQuery 从脚本调用脚本
【发布时间】:2015-07-06 22:21:48
【问题描述】:

我在执行脚本时遇到了一些困难。我是 HTML 和 JQuery 的新手。

使用 Google 表格和 Google Apps 脚本:

我有 3 个文件有问题:

'sidebar.html'
'popup.html'
'scriptsJS.html'

'sidebar' 和 'popup' 的脚本都在 'scriptsJS' 中。

按钮“#btnRefreshData”绑定到'sidebar'中的按钮;此按钮和相关脚本按预期工作。

我正在尝试从绑定到“popup.html”中不同按钮的另一个脚本触发相同的按钮,但调用被忽略。

下面的脚本在'scriptsJS.html'中,并绑定到'popup.html'中的一个按钮:

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

    this.disabled = true;
    var item = $( "#resultsList" ).find(':selected').val();  

    google.script.run
        .withSuccessHandler(
          function(msg, element) {
            element.disabled = false;
            doThis(); 
            google.script.host.close();
            })   

        .withFailureHandler(
          function(msg, element) {
            showStatus(msg, 'error');
            element.disabled = false;
          })

        .withUserObject(this)

        .openSelectedItem(item);
  });

上面的脚本执行正确;我的数据加载,然后它调用'doThis':

function doThis () {
     alert ('do this called');
     $( "#btnRefreshData" ).trigger( "click" );  //<-- ignored
};

上面的脚本成功显示警报(用于测试),然后尝试触发#btnRefreshData。 #btnRefreshData 绑定到“sidebar.html”,并导致侧边栏中的数据重新填充。

同样,所有这些脚本都在同一个文件中,但是当我从“popup.html”调用#btnRefreshData(绑定到“sidebar.html”)时,它被忽略了。

我希望找到一种方法来触发此事件。谢谢你能给我的任何帮助。

【问题讨论】:

    标签: javascript jquery google-apps-script google-apps


    【解决方案1】:

    我猜这是一个事件委托问题,你如何绑定#btnRefreshData 的点击处理程序?如果您不委托它,请尝试按如下方式委托它:

     $( "#btnRefreshData" ).on( "click", function() {} ); //My guess on how you are binding it.
    
     $( document ).on( "click", "#btnRefreshData", function() {} ); //Delegating the event.
    

    【讨论】:

    • 谢谢你,taxicala...不幸的是,我无法让它工作。加载时, $( document ).ready(function() { $( "#btnRefreshData" ).trigger( "click" ); });在我将其更改为“委托”样式绑定后,未能触发此按钮的单击事件。感谢您的反馈,不过......我很感激。
    【解决方案2】:

    Apps 脚本使用 caja 来编译代码。对于设计,您可以在普通 javascript 上获得的一些选项被禁用,并且以编程方式触发点击就是其中之一。这就是您提到的代码被忽略的原因。 在这种情况下,最好调用在您的 doThis 方法中单击“#btnRefreshData”按钮时执行的方法。

    您可以在这里找到一些解释:https://code.google.com/p/google-caja/issues/detail?id=1404 https://developers.google.com/apps-script/guides/html/restrictions#restrictions_in_native_and_emulated_mode

    【讨论】:

    • 谢谢杰拉尔多。这听起来很完美,所以我将所有方法都移到了 doThis 中,但没有运气。被调用的方法从 sidebar.html 中的元素读取值。当 sidebar.html 调用 doThis 时,它可以正常工作,但是当 popup.html 调用 doThis 时,方法会失败。我能够拦截一个失败处理程序,它返回“NetworkError:由于 HTTP 0 导致连接失败”。我认为 popup.html 不能利用 sidebar.html 页面上的元素绑定?
    猜你喜欢
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多