Javascript在IPython和Jupyter Notebook中不起作用

时间:2019-10-23 11:55:35

标签: javascript jquery html jupyter-notebook ipython

我正在尝试将日期时间选择器小部件添加到我的jupyter笔记本APP。所以我从here

获得了代码

无论如何,我将代码放入单元格中,但是它只显示输入表单,单击时什么也没发生。
我通过创建一个.html文件来测试代码,它可以正常工作,但是在jupyter Notebook中却无法。 only an empty form is shown as you can see on this pic

from IPython.display import display, HTML

html_code = '''
<head>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

</head>

<body>

<input type="text" name="datetimes" />

<script>
$(function() {
  $('input[name="datetimes"]').daterangepicker({
    timePicker: true,
    startDate: moment().startOf('hour'),
    endDate: moment().startOf('hour').add(32, 'hour'),
    locale: {
      format: 'M/DD hh:mm A'
    }
  });
});
</script>
</body>



'''

display(HTML(html_code))

1 个答案:

答案 0 :(得分:0)

您可以使用jp_proxy_widget来实现所需的功能。以下是Python代码:

import jp_proxy_widget
from jp_proxy_widget import js_context

js1 = "https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"
js2 = "https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"
css = "https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css"

# Create a proxy widget to hold the input element.
widget = jp_proxy_widget.JSProxyWidget()

# load the style and JS libraries
widget.load_css(css)
widget.load_js_files([js1, js2])

# Store the value from the date/time input in the Python variable 'value'
value = "No value yet."

def change_value(v):
    global value
    value = v

# Initialize the proxy widget with an input element configured using
# daterangepicker.
widget.js_init("""

    element.empty()
    var input = $('<input type="text" name="datetimes" size="100"/>').appendTo(element);
    input.daterangepicker({
    timePicker: true,
    startDate: moment().startOf('hour'),
    endDate: moment().startOf('hour').add(32, 'hour'),
    locale: {
       format: 'M/DD hh:mm A'
     }
  });
  // when the input changes send the value back to python
  input.change(function() { change_value(input.val());} );
  change_value(input.val());

""", change_value=change_value)

# Display the widget
widget

以下是在Jupyter中执行的代码的屏幕截图:

enter image description here

有关jp_proxy_widget的更多信息,请访问此处:https://github.com/AaronWatters/jp_proxy_widget