addTask
Description
添加一个新任务
addTask: (task: NewTask, parent?: string | number, index?: number) => string | number
Parameters
task- (required) NewTask - 任务对象parent- (required) string | number - 可选,父任务的idindex- (optional) number - 可选,任务插入的位置(0或更高)
Returns
id- (string, number) - 任务的id
Example
const taskId = gantt.addTask({
id: 10,
text: "Task #5",
start_date: "02-09-2025",
duration: 28
}, "project_2", 1);
Details
当你提供 index 参数且其值为0或更大时,任务将被插入到该分支的指定位置。 如果不提供该参数,任务将默认添加到分支的末尾。
此方法会触发 onBeforeTaskAdd 和 onAfterTaskAdd 事件。
请注意,如果你想避免保存任务--例如用户在 lightbox 中取消操作时--可以考虑使用 createTask 方法,该方法会触发 onTaskCreated 事件。
阻止在某些层级添加任务
阻止用户在某些任务下添加子任务的简单方法是通过 CSS 隐藏"Add"按钮。
- 首先,使用 grid_row_class 模板为每个任务行分配一个 CSS 类:
gantt.templates.grid_row_class = (start, end, task) => {
if (task.$level > 1) {
return "nested_task";
}
return "";
};
- 接着,隐藏这些行的"Add"按钮:
.nested_task .gantt_add{
display: none !important;
}
注释
Sample: Predefined Project Structure
Related API
Related Guides
Need help?
Got a question about the documentation? Reach out to our technical support team for help and guidance. For custom component solutions, visit the Services page.