取消按钮 UI 提示

Cancel Button UI Prompt

所以我制作的提示对话框有点问题。此代码的工作方式是每当有人在 ui 提示上点击取消时,它会取消第一个提示,但随后会出现第二个提示。有没有办法让它在有人点击取消按钮时取消两个提示?我不确定这是否有意义,但这是我的代码。

function Cancel() {
  var ui = SpreadsheetApp.getUi();

  var result = ui.prompt(
      'What Day Was Safe Rides Cancelled?',
      'Please Enter the Date as mm/dd/yyy.',
      ui.ButtonSet.OK_CANCEL);

  var result2 = ui.prompt(
      'What is the Reason for the Cancellation?',
      ui.ButtonSet.OK_CANCEL);

  // Process the user's response.
  var button = result.getSelectedButton();
  var text = result.getResponseText();
  var text2 = result2.getResponseText();
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Nightly Stats'),
    row = sheet.getLastRow();

  if (button == ui.Button.OK) {
    // User clicked "OK".
    sheet.insertRowAfter(row);
      sheet.getRange(row+1,1).setValue(text).setHorizontalAlignment("center");
      sheet.getRange(row+1,2,1,6).setValue(text2).setHorizontalAlignment("center").mergeAcross();
      sheet.getRange(row+1,8).setValue("1").setHorizontalAlignment("center");
    ui.alert('The Cancellation has Been Recorded');
  } else if (button == ui.Button.CANCEL) {
    // User clicked "Cancel".
    ui.alert('You closed the dialog.');
  } else if (button == ui.Button.CLOSE) {
    // User clicked X in the title bar.
    ui.alert('You closed the dialog.');
  }
}

如果您能提供任何帮助,我们将不胜感激。谢谢!

您基本上需要将 "result2" 提示逻辑移动到 if (button == ui.Button.OK) {...} 部分。

此外,我建议将 "insertData" 的东西重构到它自己的函数中,这样 button/prompt 逻辑更容易理解。

像这样:

var SS = SpreadsheetApp.getActiveSpreadsheet();

function Cancel() {
  var ui = SpreadsheetApp.getUi();

  // first prompt
  var result = ui.prompt(
    "What Day Was Safe Rides Cancelled?",
    "Please Enter the Date as mm/dd/yyy.",
    ui.ButtonSet.OK_CANCEL
  );
  var button = result.getSelectedButton();
  var text = result.getResponseText();

  // User clicked "OK" on first prompt
  if (button == ui.Button.OK) {
    // second prompt
    var result2 = ui.prompt(
      "What is the Reason for the Cancellation?",
      ui.ButtonSet.OK_CANCEL
    );
    var button2 = result2.getSelectedButton();
    var text2 = result2.getResponseText();

    // user clicked "OK" on second prompt
    if (button2 == ui.Button.OK) {
      insertData(text, text2);
    }
  }
}

function insertData(text, text2) {
  // get last row in nightly stats sheet
  var sheet = SS.getSheetByName("Nightly Stats");
  row = sheet.getLastRow();

  // insert data into sheet
  sheet.insertRowAfter(row);
  sheet
    .getRange(row + 1, 1)
    .setValue(text)
    .setHorizontalAlignment("center");
  sheet
    .getRange(row + 1, 2, 1, 6)
    .setValue(text2)
    .setHorizontalAlignment("center")
    .mergeAcross();
  sheet
    .getRange(row + 1, 8)
    .setValue("1")
    .setHorizontalAlignment("center");
}