
本文详解如何根据窗口宽高动态添加/移除 jquery 点击事件监听器,避免重复绑定导致的多次触发问题,并提供可复用的响应式事件管理方案。
本文详解如何根据窗口宽高动态添加/移除 jquery 点击事件监听器,避免重复绑定导致的多次触发问题,并提供可复用的响应式事件管理方案。
在响应式开发中,常需根据不同屏幕方向(如 portrait / landscape)启用或禁用特定交互逻辑。但若直接在 resize 回调中反复调用 $("#btn").click(...),会导致事件处理器被不断叠加——每次调整窗口大小都会新增一个监听器,最终点击一次触发多次弹窗,这是典型的事件重复绑定问题。
根本原因在于:.click(handler) 是 .on('click', handler) 的简写,但它不具备移除能力;而真正可管理的事件绑定必须使用 .on() 配合 .off(),且需确保传入 .off() 的函数引用与 .on() 中完全一致。
✅ 正确做法:将事件处理函数定义为具名函数,并在尺寸切换时按需绑定/解绑:
jQuery 1.12.4是jQuery 1.x系列的最后一个正式稳定版本,由jQuery团队于2016年发布。该版本主要面向需要兼容旧版浏览器环境的网站和Web应用,尤其适用于仍需支持Internet Explorer 6、Internet Explorer 7、Internet Explorer 8等老旧浏览器的项目。
// 定义具名函数(便于后续精准移除)
function showPortraitAlert() {
alert("Portrait mode: This is an alert message!");
}
function showLandscapeAlert() {
alert("Landscape mode: Action disabled or modified.");
}
var widthThreshold = 575;
var heightThreshold = 575;
function ScreenTrigger() {
const $display = $('.display');
const $btn = $('#btn');
// 先统一清理可能存在的旧监听器(安全兜底)
$btn.off('click', showPortraitAlert);
$btn.off('click', showLandscapeAlert);
if (window.innerWidth < widthThreshold && window.innerHeight >= heightThreshold) {
// 视为 portrait(宽窄高长)
$display.removeClass('landscape').addClass('portrait');
$btn.on('click', showPortraitAlert);
} else if (window.innerHeight < heightThreshold && window.innerWidth >= widthThreshold) {
// 视为 landscape(宽长大高短)
$display.removeClass('portrait').addClass('landscape');
$btn.on('click', showLandscapeAlert);
} else {
$display.removeClass('portrait landscape');
// 无匹配状态时也可选择禁用按钮交互
}
}
// 使用防抖优化 resize 性能(强烈推荐)
function debounce(func, wait) {
let timeout;
return function executedFunction() {
const later = () => {
clearTimeout(timeout);
func.apply(this, arguments);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
window.addEventListener('resize', debounce(ScreenTrigger, 150));
ScreenTrigger(); // 初始化执行⚠️ 关键注意事项:
-
不可内联匿名函数:
$('#btn').on('click', function(){...})后无法用.off('click', function(){...})移除,因每次创建的是新函数实例; -
优先
.off()再.on():在每次ScreenTrigger中先解绑再绑定,防止残留; -
防抖必不可少:
resize事件高频触发,不加防抖将导致大量无效计算和绑定/解绑开销; -
语义化判断更可靠:仅依赖
innerWidth/innerHeight数值易受滚动条、缩放等干扰,生产环境建议结合matchMedia或 CSS 媒体查询钩子(如window.matchMedia('(orientation: portrait)'))增强鲁棒性。
总结:jQuery 事件的“取消”本质是事件委托的显式解绑,核心在于函数引用一致性与生命周期可控性。通过分离逻辑、命名处理函数、配合防抖与精准解绑,即可实现干净、可维护的响应式交互控制。

















