如何用jQuery遍历HTML区块并提取多类数据至数组?
问题场景与需求
有多个结构一致的.customers__photo HTML区块(示例结构如下),需要通过jQuery提取每个区块内的:
.infoblock__user-name的内容.infoblock__date的内容.infoblock__text的内容- 内部
img的src属性值
将这些数据整理为数组后,通过console.log遍历输出所有值。
示例HTML结构
<div class="customers__photo" data-id="a1"> <div class="infoblock infoblock-hidden"> <div class="infoblock__user-name"><strong>Alexander</strong></div> <div class="infoblock__date">21 August 2022</div> <div class="infoblock__text">Comportable table</div> </div> <img src="girl1.jpg" class="reviews__photo"> </div>
原代码的问题
你尝试的代码存在几个关键问题:
- 错误选择单个元素集合而非遍历父区块,全局选择器只会取第一个匹配项
map函数内部未返回完整数据结构,逻辑混乱forEach参数使用错误(仅接收item、index、array三个参数,无法直接解构四个变量)
修正后的解决方案
核心思路是先遍历每个父区块.customers__photo,对每个区块内部用相对选择器提取数据,将每个区块的信息封装为对象,最后收集成数组再遍历输出。
完整代码
// 遍历所有用户区块,提取每个区块的完整信息并转为普通数组 const customerData = $('.customers__photo').map(function() { const $currentBlock = $(this); return { name: $currentBlock.find('.infoblock__user-name').html(), date: $currentBlock.find('.infoblock__date').text(), text: $currentBlock.find('.infoblock__text').text(), imgSrc: $currentBlock.find('img').attr('src') }; }).get(); // 遍历数组,输出每个区块的信息 customerData.forEach(function(item) { console.log('姓名:', item.name, '日期:', item.date, '评价:', item.text, '图片地址:', item.imgSrc); // 如需追加图片到页面,可取消下面注释 // $('.listblock').append(`<img class="listblock__photo" src="${item.imgSrc}">`); });
关键说明
- 用
$('.customers__photo').map()遍历每个独立区块,确保数据对应关系正确 - 用
$currentBlock.find()做相对选择,避免全局选择器的错误匹配 - 将每个区块的信息封装为对象,数组元素结构清晰,遍历逻辑更直观
get()方法将jQuery集合转为普通JS数组,方便后续操作
内容的提问来源于stack exchange,提问作者Azizxon Zufarov
相关产品推荐
相关产品推荐

