Rails 7中jQuery转原生JS实现悬停弹窗失效问题求助
问题分析与解决方案
当前代码的核心错误
- 混用jQuery与原生API:
$(document)是jQuery对象,不能直接调用原生的addEventListener;同时$('#info_1')这类jQuery选择器如果未引入jQuery会直接报错,原生JS需用document.getElementById获取元素。 - 事件绑定方式错误:原生JS的
onmouseover无法同时绑定鼠标进入/离开两个回调,需分别绑定mouseover和mouseout事件。 - 方法调用错误:
.show()/.hide()是jQuery专属方法,原生JS需通过操作元素的style.display属性控制显示隐藏。 - Turbo环境适配问题:Rails 7的Turbo采用增量页面加载,
DOMContentLoaded仅在初始页面加载时触发,后续导航不会重新执行绑定逻辑,需改用Turbo专属事件。
修正后的原生JS实现(适配Turbo)
将代码放在app/javascript/custom/menu.js中,确保已在app/javascript/application.js中导入(添加import "../custom/menu"):
document.addEventListener("turbo:load", function() { const infoElement = document.getElementById('info_1'); const popupElement = document.getElementById('popup_1'); // 定义复用的回调函数 function showPopup() { popupElement.style.display = 'block'; } function hidePopup() { popupElement.style.display = 'none'; } // 先移除旧监听避免重复绑定 infoElement.removeEventListener('mouseover', showPopup); infoElement.removeEventListener('mouseout', hidePopup); // 绑定新事件 infoElement.addEventListener('mouseover', showPopup); infoElement.addEventListener('mouseout', hidePopup); });
额外检查项
- 确保弹窗元素
popup_1的初始CSS样式为display: none;,否则默认会显示。 - 如果仍需保留jQuery(项目已引入),可简化为:
$(document).on('turbo:load', function() { $('#info_1').hover( () => $('#popup_1').show(), () => $('#popup_1').hide() ); });
内容的提问来源于stack exchange,提问作者user3763682
相关产品推荐
相关产品推荐

