如何使用jQuery为所有相同class的元素绑定事件监听器
现有代码错误点
- 选择器书写错误:绑定点击事件时使用的
$('project')是标签选择器,你需要选中类名为project的元素,要补充类选择器标识.,改为$('.project') - DOM对象与jQuery对象混淆:通过
$('.project')[i]获取到的是原生DOM元素,不存在jQuery提供的click()方法,需要转为jQuery对象后才能调用对应的jQuery方法 - 逻辑冗余:jQuery本身支持给所有匹配选择器的元素批量绑定事件,不需要额外写
each循环遍历
完整模态框实现方案
1. 新增模态框HTML结构
你可以把这段代码加在现有HTML的body标签末尾:
<div class="modal" id="projectModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 999;"> <div class="modal-content" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background: #fff; padding: 20px; border-radius: 8px; width: 80%; max-width: 600px;"> <span class="close-modal" style="position: absolute; right: 15px; top: 10px; font-size: 24px; cursor: pointer;">×</span> <h3 class="modal-title"></h3> <img class="modal-img" src="" alt="" style="width: 100%; margin: 15px 0;"> </div> </div>
2. 替换原有jQuery逻辑
// 给所有项目卡片绑定点击事件 $('.project').click(function() { // 读取当前点击卡片的内容 const currentTitle = $(this).find('.project-title').text(); const currentImg = $(this).find('img').attr('src'); // 填充模态框内容 $('.modal-title').text(currentTitle); $('.modal-img').attr('src', currentImg); // 显示模态框 $('#projectModal').fadeIn(); }); // 点击关闭按钮隐藏模态框 $('.close-modal').click(function() { $('#projectModal').fadeOut(); }); // 点击模态框空白区域关闭 $('#projectModal').click(function(e) { if($(e.target).is('#projectModal')) { $(this).fadeOut(); } });
内容的提问来源于stack exchange,提问作者pNut
相关产品推荐
相关产品推荐

