Word加载项实现下拉显隐按钮后 文本插入按钮功能失效
问题原因
按钮点击失效是两个代码问题共同导致的:
- 重复加载jQuery:你在页面head区域引入了一次本地jQuery,body末尾又引入了一次CDN版本的jQuery,第二次加载jQuery会覆盖之前的实例,把之前在Home.js里给按钮绑定的点击事件全部清空。
- 事件绑定逻辑有缺陷:你给按钮绑定点击事件时,按钮所在的容器默认被CSS设置为隐藏状态,后续下拉切换显示的逻辑没有做兼容事件绑定,加上jQuery实例被覆盖,点击事件自然不会触发。
修复方案
按以下步骤调整代码即可:
- 删除head区域重复的本地jQuery引用,只保留body末尾的一个jQuery引用即可,同时把Home.js的引用挪到jQuery引用的后面,保证脚本加载顺序正确:先加载jQuery,再加载依赖jQuery的业务逻辑。
- 把直接给按钮绑定事件的写法换成事件委托,这种方式不依赖元素初始显示状态,就算元素后续隐藏、动态显示都不会丢失事件。把Home.js里原来的事件绑定代码:
$('#rogincorporate').click(insertRogIncorporate);
替换为:
$(document).on('click', '#rogincorporate', insertRogIncorporate);
- 可选修复:你在内联样式里重写了
.padding类的样式,覆盖了原CSS里的15px内边距规则,会导致头部标题贴边,给内联的.padding规则补上padding:15px;属性即可。
修复后核心代码参考
Home.js 初始化部分
'use strict'; (function () { Office.onReady(function () { if (Office.context.requirements.isSetSupported('WordApi', '1.1')) { // 用事件委托绑定按钮点击 $(document).on('click', '#rogincorporate', insertRogIncorporate); $('#supportedVersion').html('This code is using Word 2016 or later.'); // 下拉框切换逻辑统一放到初始化回调里,保证Office和DOM都加载完再执行 $("#name").on('change', function () { $(".data").hide(); $("#" + $(this).val()).fadeIn(700); }).change(); } else { $('#supportedVersion').html('This code requires Word 2016 or later.'); } }); async function insertRogIncorporate() { await Word.run(async (context) => { const thisDocument = context.document; const range = thisDocument.getSelection(); range.insertText('"Responding Party adopts and incorporates the General Response and Objections above in response to this interrogatory as though separately set forth herein. "\n', Word.InsertLocation.replace); await context.sync(); console.log('Added a incorporate text.'); }).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); if (error instanceof OfficeExtension.Error) { console.log('Debug info: ' + JSON.stringify(error.debugInfo)); } }); } })();
HTML脚本引用部分调整
删掉head里的本地jQuery引用,把所有非Office.js的脚本挪到body末尾:
<!-- body末尾,所有页面内容后面 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="Scripts/MessageBanner.js" type="text/javascript"></script> <script src="Home.js" type="text/javascript"></script>
把原来写在body末尾script标签里的下拉框切换逻辑挪到Home.js的Office.onReady回调里即可,不用单独在HTML里写冗余内联脚本。
改完之后重新加载加载项,切换下拉项后点击按钮即可正常插入预设文本。
内容的提问来源于stack exchange,提问作者CasusBelli
相关产品推荐
相关产品推荐

