Jupyter笔记本:按钮onclick在运行的笔记本中不起作用

时间:2017-07-13 16:12:43

标签: javascript jupyter-notebook ipython-notebook

我可以使用IPython.display.Javascript在单独的标签页中同时打开多个源文档,以帮助简化错误分析工作流程。

# This opens all links in new tabs upon cell execution

def open_all(links):
    # Set up onclick function
    javascript = "\n".join(['window.open("{}");'.format(link) for link in links])
    return javascript

js = open_all_dockets(links)
display(Javascript(js))

我真正想做的是能够将新标签中的这些链接的开头绑定到按钮。这将允许笔记本用户执行所有单元格并仍然通过单击控制打开哪组源文档。

问题是这只有在笔记本电脑呈现为HTML时才有效。

# The button opens links in new tabs *only* once the notebook is rendered to HTML

def open_all_button(links):
    # Set up onclick function
    onclick =  "function open() {\n"
    onclick += "\n".join([" "*4 + 'window.open("{}");'.format(link) for link in links])
    onclick += "}\n"
    # Create button
    button = "element.append('<button onclick={}>one click open source docs</button>')".format('"open()"')
    # Assemble JS
    javascript = onclick + button
    return javascript

display(Javascript(open_all_button(links)))

如何在正在运行的笔记本中使用它?

感谢。

1 个答案:

答案 0 :(得分:1)

我已经乱七八糟了,这似乎适用于现场笔记本和输出为html。我猜测单独定义的open()函数搞砸了,所以我们只需在按钮本身的onclick属性中定义它。

# The button opens links in new tabs *only* once the notebook is rendered to HTML
import IPython.display as display
def open_all_button(links):
    # Set up onclick function
    onclick = "".join(['window.open("{}");'.format(link) for link in links])
    # Create button
    javascript = "element.append('<button onclick=" + onclick +">one click open source docs</button>')"
    return javascript

display.Javascript(open_all_button(["https://www.google.com","https://www.google.co.uk"]))