jQuery如何为每个.content-cont容器内的p元素分别创建独立数组
问题解决方案
问题原因
你原先的写法$( ".content-cont p" ).toArray()会全局选中所有.content-cont下的p元素,没有按父容器拆分,所以得到的是所有p合并的大数组。你后续参考代码里的$(el).find('p')其实已经拿到了单个容器内的p元素集合,只要调用toArray()就能得到对应容器的独立p数组。
单独生成每个容器p数组的代码
// 外层数组,每一项对应一个.content-cont内部的p标签数组 const allContainerParas = [] $('.content-cont').each((i, el) => { // 单个容器内的p标签数组 const currentParaArr = $(el).find('p').toArray() allContainerParas.push(currentParaArr) }) console.log(allContainerParas)
修正后的完整功能代码
你后续参考代码里存在选择器范围问题,$('.content-cont .media-cont')会选中所有容器内的媒体容器,需要限定在当前遍历的容器内:
$('.content-cont').each((i, el) => { // 限定只选当前容器内的media-cont const $img = $(el).find('.media-cont'); const $p = $(el).find('p'); const mid = Math.floor($p.length / 2); const $middle = $p.eq(mid); $middle.addClass('middle'); $middle.before($img); });
内容的提问来源于stack exchange,提问作者jmcgrother
相关产品推荐
相关产品推荐

