You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Databricks笔记本中实现单元格控制与JavaScript弹窗?

Azure Databricks 替代 Jupyter 功能实现方案

问题背景

我正在Azure Databricks笔记本中复现Jupyter里的三个功能,但原Jupyter代码在Databricks中无效,原Jupyter代码示例如下:

示例1:Jupyter中控制单元格可见性

from IPython.display import HTML, Javascript, display as IPyDisplay, clear_output

HTML('''
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function code_toggle(){
            if (code_shown){
                $('div.input').hide('500');
                $('#toggleButton').val('Show Code')
            } 
            else {
                $('div.input').show('500');
                $('#toggleButton').val('Hide Code')
            }
            code_shown = !code_shown
        }

        $(document).ready(function(){
            code_shown=false;
            $('div.input').hide()
        });
    </script>
    <form action="javascript:code_toggle()">
        <input type="submit" id="toggleButton" value="Show Code">
    </form>
''')

示例2:Jupyter中触发JS弹窗

from IPython.display import display, Javascript

display(Javascript("""
alert('Hello, this is a JavaScript alert!');
"""))

示例3:Jupyter中执行后续单元格

display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.ncells())'))

需要在Azure Databricks中实现以下功能:

  • 控制单元格可见性
  • 按cell_id执行同一笔记本内的单元格
  • 触发JavaScript弹窗或其他客户端JS功能

解决方案

1. 控制单元格可见性

Databricks的DOM结构与Jupyter不同,需适配其单元格代码区域的选择器。以下代码可实现代码块的显示/隐藏切换:

from IPython.display import HTML, display

display(HTML('''
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
let codeVisible = false;

function toggleCode() {
  codeVisible = !codeVisible;
  const codeBlocks = document.querySelectorAll('.dbsql-cell-code');
  codeBlocks.forEach(block => {
    block.style.display = codeVisible ? 'block' : 'none';
  });
  document.getElementById('toggleBtn').textContent = codeVisible ? '隐藏代码' : '显示代码';
}

// 初始隐藏代码块
document.addEventListener('DOMContentLoaded', () => {
  const codeBlocks = document.querySelectorAll('.dbsql-cell-code');
  codeBlocks.forEach(block => {
    block.style.display = 'none';
  });
});
</script>
<button id="toggleBtn" onclick="toggleCode()">显示代码</button>
'''))

注:若.dbsql-cell-code选择器不生效,可通过浏览器开发者工具查看Databricks单元格代码区域的实际类名替换。

2. 按cell_id执行同一笔记本内的单元格

Databricks提供前端API用于执行指定单元格,需先获取目标单元格的cellId(可通过浏览器开发者工具在单元格元素的data-cell-id属性中找到):

from IPython.display import display, Javascript

# 替换为目标单元格的cellId
target_cell_id = "your-cell-id-here"

display(Javascript(f'''
// 执行指定单元格
Databricks.notebook.executeCell("{target_cell_id}");
'''))

若需执行当前单元格之后的所有单元格,可通过遍历单元格ID实现:

display(Javascript('''
// 获取当前选中单元格索引
const currentCell = Databricks.notebook.getSelectedCell();
if (currentCell) {
  const allCells = Array.from(document.querySelectorAll('[data-cell-id]'));
  const currentIndex = allCells.findIndex(cell => cell.dataset.cellId === currentCell.dataset.cellId);
  // 执行当前单元格之后的所有单元格
  for (let i = currentIndex + 1; i < allCells.length; i++) {
    Databricks.notebook.executeCell(allCells[i].dataset.cellId);
  }
}
'''))

3. 触发JavaScript弹窗或客户端JS功能

Databricks限制了原生alert弹窗的显示,可通过以下两种方式替代:

方式1:自定义HTML模态弹窗

from IPython.display import HTML, display

display(HTML('''
<div id="customModal" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); padding:20px; background:white; border:1px solid #ccc; z-index:9999;">
  <p>Hello, this is a custom alert!</p>
  <button onclick="document.getElementById('customModal').style.display='none'">关闭</button>
</div>

<button onclick="document.getElementById('customModal').style.display='block'">触发弹窗</button>
'''))

方式2:使用Databricks通知API

# 显示右上角通知
dbutils.notebook.showHTML('''
<script>
Databricks.ui.toast.success('操作完成!', {duration: 3000});
// 支持success/info/warning/error四种类型
</script>
''')

内容的提问来源于stack exchange,提问作者9879ypxkj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:16:20