jQuery each函数使用方法及循环获取href对应显示的问题咨询
jQuery each函数使用方法及循环获取href对应显示的问题咨询
看起来你遇到了一个很典型的jQuery选择器和DOM元素唯一性的问题,我来帮你理一理~
首先说问题出在哪:你页面里重复使用了id="thelink",但HTML里的ID是唯一标识,浏览器和jQuery在查找ID的时候,只会返回第一个匹配到的元素,所以你每次循环append的时候,都把href加到了第一个#thelink div里,这就导致所有URL都堆在第一个盒子里了。
接下来给你一套完整的解决方案:
第一步:修改HTML结构
把所有重复的id="thelink"改成class="thelink",因为class是可以重复使用的,完全适合这种需要多个同类型容器的场景:
<script src="jquery.min.js"></script> <h3 class="post-title entry-title"> <a href="https://example.com/example1.html">Example 1</a> </h3> <div class="thelink"></div> <h3 class="post-title entry-title"> <a href="https://otherexample.com/example2.html">Example 2</a> </h3> <div class="thelink"></div> <h3 class="post-title entry-title"> <a href="https://thirdexample.com/example3.html">Example 3</a> </h3> <div class="thelink"></div>
第二步:调整jQuery代码
在each循环里,我们需要精准定位到当前a标签对应的那个.thelink容器。这里可以用closest()找到当前a所在的h3元素,再用next()找到h3后面紧邻的.thelink容器,这样就能把href放到对应的位置了:
jQuery(document).ready(function() { $("h3.post-title a").each(function(){ var thelink = this.href; // 找到当前a标签对应的专属容器 $(this).closest('h3').next('.thelink').append(thelink); }); });
这样修改之后,每个a标签的href就会被精准插入到它自己对应的.thelink容器里,不会再出现全部堆在第一个盒子的问题了。另外再提一句小建议:以后写HTML的时候要注意ID的唯一性,这是前端基础里很重要的一点哦~
内容来源于stack exchange
相关产品推荐
相关产品推荐

