javascript - 如何在 Jupyter 笔记本中将 HTML 元素与 Python 函数链接?
问题描述
我编写了显示自定义右键菜单的 JavaScript 代码。
我想知道如何在我的菜单项被点击时触发 Python 函数。这些菜单项是嵌套在具有 menu 类的 div 下的 div,因此它是我的 HTML 正文部分中的唯一元素。
我使用的环境是 Jupyter Notebook。笔记本。
import jinja2
from bokeh.embed import components
template = jinja2.Template("""
<!doctype html>
<html>
<head>
<script>
src="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.js"
var menuDisplayed = false;
var menuBox = null;
window.addEventListener("contextmenu", function() {
var left = arguments[0].clientX;
var top = arguments[0].clientY;
menuBox = window.document.querySelector(".menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
arguments[0].preventDefault();
menuDisplayed = true;
}, false);
window.addEventListener("click", function() {
if(menuDisplayed == true){
menuBox.style.display = "none";
}
}, true);
</script>
<style>
.menu
{
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
padding-left: 5px;
padding-right: 5px;
padding-top: 3px;
padding-bottom: 3px;
position: fixed;
display: none;
}
.menu-item
{
height: 20px;
}
.menu-item:hover
{
background-color: #6CB5FF;
cursor: pointer;
}
</style>
</head>
<body>
<div class="menu">
<div class="menu-item">Add Node</div>
<div class="menu-item">Delete Node</div>
<div class="menu-item">Update Node</div>
</div>
</body>
</html>
""")
解决方案
我认为您将通过以下示例轻松地对此有清晰的理解和清晰度:
// %%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`print(${python})`, callbacks);
});
}
// Use it in any Jupyter JS/HTML cell like this
%%javascript
window.executePython("1 + 1")
.then(result => console.log(result)); // Logs 2
// You can access any defined object/method in the notebook
// I suggest writing a function that returns your data as JSON and just calling the function.
推荐阅读
- vue.js - NuxtJS - 将所有错误的 url 重定向到 404 页面
- javascript - 如何使用 Angular 获取典型的 json 数据
- animation - 如何在 Flutter 中创建滑入滑出动画?
- javascript - React Contenteditable - 如何将 onClick 分配给react-contenteditable?
- c++ - FindCirclesGrid c++11 不起作用,尽管检测器找到了所有点
- linux - 用 LD_LIBRARY_PATH 覆盖 BLAS
- c# - 当父对象移动时,如何防止子对象滑离父对象?
- html - 未处理嵌套 div 中的 Markdown
- java - Java 无法解析的日期 SimpleDateFormat
- javascript - 从 laravel balde 获取 foreach 循环的值并将其传递给 javascript 函数