如何通过jQuery选中卡片内<a>标签实现整张卡片点击跳转功能
完全可以通过jQuery实现该效果,无需修改现有HTML结构,具体方案如下:
实现思路
- 给卡片绑定点击事件,不改动原有DOM结构
- 点击时自动提取当前卡片内部链接的跳转地址
- 兼容原生链接的使用习惯,保留Ctrl/Command点击新开标签页的特性
- 排除用户直接点击卡片内原有链接的场景,避免重复触发跳转逻辑
实现代码
适配动态渲染场景(推荐,适配你的owl-carousel轮播结构)
因为你使用了owl轮播组件,卡片可能是动态渲染的,使用事件委托绑定到页面初始化就存在的父级元素上,不会出现动态新增的卡片无点击事件的问题:
$('.todays-news').on('click', '.card', function(e) { // 如果用户直接点击了卡片内的原有链接,不额外处理 if ($(e.target).closest('a').length) return; const targetLink = $(this).find('.card-body a').attr('href'); // 兼容Ctrl/Command点击新开标签页的操作习惯 if (e.ctrlKey || e.metaKey) { window.open(targetLink, '_blank'); } else { window.location.href = targetLink; } });
静态卡片场景(仅适用于页面加载完成后卡片不会动态新增的情况)
$('.card').on('click', function(e) { if ($(e.target).closest('a').length) return; const targetLink = $(this).find('.card-body a').attr('href'); if (e.ctrlKey || e.metaKey) { window.open(targetLink, '_blank'); } else { window.location.href = targetLink; } });
可选体验优化
添加如下CSS样式,给卡片加手型光标,提示用户卡片可点击:
.card { cursor: pointer; }
内容的提问来源于stack exchange,提问作者user17144244
相关产品推荐
相关产品推荐

