javascript - 在编辑时将多个功能应用于单元格的 JS 代码
问题描述
我目前正在尝试在 google sheet 上的脚本编辑器中编写一些 JS,不仅可以生成时间戳以及单击的复选框,还可以设置一个计时器,如果该框检查超过 X 分钟,则单元格将开始变红。
此外,当我取消选中该框以使单元格变为绿色时。这背后的想法是当我单击表示表已满时间戳的框时想到餐厅女主人的范式,给了我复选框被选中的时间并且颜色显示它不可用 - 如果我取消选中复选框,它会给出时间戳,它也没有被选中重置时间计数器并将单元格更改回绿色。目前,我可以让时间戳部分与我编写的代码一起使用,并在第一次编辑时更改颜色,但它不会根据复选框在颜色之间摇摆不定
以下是我目前拥有的代码。是否会使用触发功能或其他编辑功能如果有人有任何提示或想法,将不胜感激
- 对于视觉,我引用的每一列都是停滞的第 1 列,它是座位号,复选框位于第 2 列,第 3 列填充复选框被选中和取消选中的时间
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == "Sheet1") { //checks that we're on the correct sheet
var r = s.getActiveCell();
if (r.getColumn() == 5) { //checks the column
var nextCell = r.offset(0, 1);
//if( nextCell.getValue() !== '' ) //is empty?
nextCell.setValue(new Date().setFontColor('green');
}
解决方案
下面的代码应该可以工作:
function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet(); // the active sheet (no need to check if the sheet == sheet1 as the active sheet will always be the one that's being edited)
var r = e.range; // the range of the edited cell
var c = r.getColumn(); // the column of the range
var timeDelay = 5; // number in seconds
var checkbox = r.getValue(); // the value of the checkbox after being edited
var date = new Date(); // the date for the timestamp
if (c == 5 && checkbox == true) { // if the checkbox has been checked, change the color to red
var nextCell = r.offset(0,1);
Utilities.sleep(timeDelay * 1000); // Utilities.sleep takes a number in milliseconds
nextCell.setValue(date).setBackground("red");
} else if (c == 5 && checkbox == false) { // if the checkbox has been unchecked, change the color to green
var nextCell = r.offset(0,1);
nextCell.setValue(date).setBackground("green");
}
}
我对您的进行了一些更改,如果您要在代码中添加更多内容(即事先声明日期,在开始时设置所有变量等),我认为从长远来看,我认为更易于阅读的内容只是个人偏好.)。
但是,这绝对是多余的,因为活动表无论如何都会返回正确的内容:
if (s.getName() == "Sheet1")
我还将 setFontColor() 更改为 setBackground() 因为听起来这是您从描述中想要的,并且认为您可能不知道该功能,尽管您当然可以将其更改回 setFontColor() 没有任何问题。
我还添加了您询问的时间延迟,尽管我不确定您为什么在这种情况下需要它。如果这不是您所说的,请随意删除这两行,其余代码仍然可以正常工作:
var timeDelay = 5; // number in seconds
和
Utilities.sleep(timeDelay * 1000);
推荐阅读
- python - Python @property 与它返回的字段相同的 id
- .net-standard - 如果 NetStandard 目标平台只是一个接口,那么您在哪里/何时编写实现?
- django - 带有从请求对象分配的字段的 Django 单元测试表单
- c# - 亚马逊销售伙伴 API 请求
- node.js - 无法按照协议解析临时密钥响应
- python - 即使输出层有任何大小,keras 神经网络如何找到要归因的类?
- python - 使用 selenium XPATH 查找元素的替代方法?
- asp.net - axios post只返回空字符串(反应)?
- ios - 没有从 UIViewController 正确调用 UICollectionViewCell
- javascript - 标记未显示在传单地图上 - 树枝位置数组到传单地图