如何解决WordPress集成Rough Notation JS库的parentElement报错
报错核心原因
Cannot read properties of null (reading 'parentElement') 报错由两个问题直接导致:
- 脚本执行时机早于页面DOM渲染完成:执行
document.querySelector查询节点时,目标元素还没被浏览器解析,查询返回null,将null传入annotate()方法后,库内部尝试读取元素的parentElement属性就会触发类型错误。 - 选择器不严谨:你使用的
em、strong、h1、span都是全局标签选择器,一旦当前页面不存在对应标签,同样会返回null触发报错;WordPress不同页面的DOM结构差异较大,不是所有页面都包含你要标注的元素。
修复方案
1. 调整JS逻辑,增加加载等待和空值校验
修改annotate-text.js的代码,等DOM完全加载完成后再执行节点查询,同时对每个查询到的节点做非空判断,节点不存在时直接跳过对应标注,避免脚本卡住:
import { annotate } from 'rough-notation'; // 建议将库文件下载到本地主题js目录引用,不要用公共CDN document.addEventListener('DOMContentLoaded', () => { // 下划线标注 const n1 = document.querySelector('em'); if (n1) { const a1 = annotate(n1, { type: 'underline', color: 'blue' }); a1.show(); } // 圆圈标注 const n2 = document.querySelector('strong'); if (n2) { const a2 = annotate(n2, { type: 'circle', color: 'red', padding: 10 }); a2.show(); } // 方框标注 const n3 = document.querySelector('h1'); if (n3) { const a3 = annotate(n3, { type: 'box', color: 'orange' }); a3.show(); } // 高亮标注:不建议直接用span标签选择器,给需要标注的元素加专属class后替换选择器 const n4 = document.querySelector('.rn-highlight'); if (n4) { const a4 = annotate(n4, { type: 'highlight', color: 'yellow', iterations: 1, multiline: true }); a4.show(); } // 括号标注 const n5 = document.querySelector('#block'); if (n5) { const a5 = annotate(n5, { type: 'bracket', color: 'red', padding: [2, 10], brackets: ['left', 'right'], strokeWidth: 3 }); a5.show(); } })
2. 修复WordPress函数的语法错误
你之前粘贴的PHP加载代码中,annotate_scripts函数缺少开头的左大括号,会触发PHP语法错误,将主题functions.php中对应的代码替换为以下版本:
function annotate_scripts() { wp_enqueue_script( 'module_handle', get_stylesheet_directory_uri() . '/js/annotate-text.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'annotate_scripts' ); function set_scripts_type_attribute( $tag, $handle, $src ) { if ( 'module_handle' === $handle ) { $tag = '<script type="module" src="'. esc_url($src) .'"></script>'; } return $tag; } add_filter( 'script_loader_tag', 'set_scripts_type_attribute', 10, 3 );
3. 优化建议
- 不要使用公共CDN导入库文件,将rough-notation的库源文件下载到你主题的js目录本地引用,避免CDN波动导致功能失效。
- 给所有需要标注的元素添加专属自定义class(比如
rn-underline、rn-circle),用专属class替代全局标签选择器,避免误选页面中其他同标签的无关元素,也能减少查询返回null的概率。
内容的提问来源于stack exchange,提问作者Mekong
相关产品推荐
相关产品推荐

