如何在Jupyter中使用JavaScript选择当前单元格? [英] How to select current cell with JavaScript in Jupyter?

查看:163
本文介绍了如何在Jupyter中使用JavaScript选择当前单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含JavaScript代码的笔记本单元格,我希望该代码选择此特定单元格.不幸的是,get_selected_cell的行为取决于我是在原地执行单元格,还是执行并选择下面的单元格.

I have a notebook cell containing JavaScript code, and I would like the code to select this particular cell. Unfortunately, the behavior of get_selected_cell depends on whether I execute the cell in place, or execute and select the cell below.

示例:

%%javascript
var cell = Jupyter.notebook.get_selected_cell();
console.log(Jupyter.notebook.find_cell_index(cell));

执行此单元格时,无论我使用Ctrl+Enter还是Shift+Enter执行,控制台输出都将不同.在一种情况下,它记录包含JavaScript代码的单元格的索引,在另一种情况下,它记录下面的单元格的索引.

When executing this cell, the console output will be different whether I execute with Ctrl+Enter or Shift+Enter. In one case it logs the index of the cell that contains the JavaScript code, in the other the index of the cell below.

有没有一种方法可以选择我想要的单元格?

Is there a way to select the cell I want?

推荐答案

您的Javascript将在应用Javascript的OutputArea上具有一个句柄,但并非一直到单元格(通常,输出区域可在没有单元格的情况下使用)或笔记本).您可以通过标识父.cell元素,然后获取与该元素对应的单元格来找到该单元格:

Your Javascript will have a handle on the OutputArea applying the Javascript, but not one all the way to the cell (in general, output areas can be used without cells or notebooks). You can find the cell by identifying the parent .cell element, and then getting the cell corresponding to that element:

%%javascript
var output_area = this;
// find my cell element
var cell_element = output_area.element.parents('.cell');
// which cell is it?
var cell_idx = Jupyter.notebook.get_cell_elements().index(cell_element);
// get the cell object
var cell = Jupyter.notebook.get_cell(cell_idx);

这篇关于如何在Jupyter中使用JavaScript选择当前单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆