首页 > 解决方案 > Toggle to hide cell output in the HTML version

问题描述

The following code displays a link that shows/hides the output of the next cell:

from IPython.display import HTML
HTML('''<script>
function code_toggle_next() {
    $('div.cell.code_cell.rendered.selected').next().find('div.output').toggle();
    }
$( document ).ready(code_toggle_next);
</script>
<a href="javascript:code_toggle_next()"> To show/hide next the output of the next cell, click here </a>.''')

However it doesn't seem to work once the notebook has been exported to HTML: the output of the next cell is displayed, and clicking on the link doesn't do anything. Any suggestion on how to fix this?

标签: javascripthtmljupyter-notebook

解决方案


When you open the HTML file and select Inspect element or DEV tools depending on your browser, you'll see that the cell misses the class selected, so the first selector returns an empty result. I tried and removing that class fixes the behaviour.

However, it returns all cells instead, so if you take .next().find('div.output') then it will apply to all but the very first cell. It's probably better to use the onclick attribute. This way, you can pass the cell you clicked on as an argument to the function (see the docs) and still toggle only the following cell. Have a look:

from IPython.display import HTML
HTML('''<script>
function toggle_next(event) {
    $(event.target).closest('div.code_cell').next().find('div.output').toggle();
}
</script>
<a onclick="toggle_next(event)"> To show/hide next the output of the next cell, click here </a>.''')

推荐阅读