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

如何在Jupyter Notebook中自动执行高亮输出内容的JavaScript代码?

可行的JavaScript自动执行方案

方法1:用IPython.display直接注入JS(含自动触发逻辑)

在Jupyter代码单元格中,通过IPython.display.JavaScript嵌入你的高亮逻辑,既可以手动运行执行,也可以监听单元格运行事件实现自动触发。

即时执行版(运行单元格后立即高亮现有输出)

from IPython.display import JavaScript

# 替换为你的高亮逻辑代码
highlight_js = """
// 遍历所有单元格输出区域
document.querySelectorAll('.output_area').forEach(area => {
  // 查找所有包含容量单位的文本元素
  const textNodes = area.querySelectorAll('div, span, p');
  textNodes.forEach(node => {
    const content = node.textContent;
    // 匹配数字+MB/GB/KB等格式
    const regex = /(\d+(?:\.\d+)?)(MB|GB|KB)/gi;
    if (regex.test(content)) {
      // 替换为带高亮样式的HTML
      node.innerHTML = content.replace(regex, '<span style="color: #dc2626; font-weight: bold;">$1$2</span>');
    }
  });
});
"""

# 执行JS代码
JavaScript(highlight_js)

自动触发版(每次单元格运行后自动高亮)

from IPython.display import JavaScript

auto_highlight_js = """
// 定义高亮函数
function highlightStorageSizes() {
  document.querySelectorAll('.output_area').forEach(area => {
    const textNodes = area.querySelectorAll('div, span, p');
    textNodes.forEach(node => {
      const content = node.textContent;
      const regex = /(\d+(?:\.\d+)?)(MB|GB|KB)/gi;
      if (regex.test(content)) {
        node.innerHTML = content.replace(regex, '<span style="color: #dc2626; font-weight: bold;">$1$2</span>');
      }
    });
  });
}

// 监听单元格执行完成事件,延迟执行确保输出渲染完毕
Jupyter.notebook.events.on('execute.CodeCell', function() {
  setTimeout(highlightStorageSizes, 500);
});

// 首次加载时执行一次高亮
highlightStorageSizes();
"""

JavaScript(auto_highlight_js)

方法2:利用单元格post_run钩子自动执行

通过注册Jupyter的post_run_cell事件钩子,让每个单元格运行结束后自动调用高亮JS:

from IPython.display import display, JavaScript
from IPython.core.getipython import get_ipython

def highlight_after_run():
    display(JavaScript("""
      document.querySelectorAll('.output_area').forEach(area => {
        const textNodes = area.querySelectorAll('div, span, p');
        textNodes.forEach(node => {
          const content = node.textContent;
          const regex = /(\d+(?:\.\d+)?)(MB|GB|KB)/gi;
          if (regex.test(content)) {
            node.innerHTML = content.replace(regex, '<span style="color: #dc2626; font-weight: bold;">$1$2</span>');
          }
        });
      });
    """))

# 注册钩子,全局生效
ip = get_ipython()
ip.events.register('post_run_cell', highlight_after_run)

注意事项

  • 上述方案适配Jupyter Classic Notebook,若使用JupyterLab,部分DOM类名(如.output_area)或事件名称可能需要调整。
  • 延迟执行的时间(如setTimeout的500ms)可根据输出渲染速度自行调整,确保高亮逻辑在输出完全生成后执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:25:07