gpt4 book ai didi

javascript/jquery - 如何从重复出现的父类中获取子类名称的变量

转载 作者:行者123 更新时间:2023-12-01 01:12:42 25 4
gpt4 key购买 nike

编辑(JSFiddle 的旧链接是错误的):JSFiddle 示例的链接:https://jsfiddle.net/uvexys0a/

我正在尝试使用 jQuery 进行编程,因此它会包装一个指向员工个人资料页面的 HTML 链接,并使用类名 staffList 包装整个每个 div。页面的路径作为子类存储在每个 div 中,如 JSFiddle 上所示。

代码似乎在某种程度上起作用了。这两个链接最终都会转到约翰·史密斯的个人资料:

<a href="https://example.com/john-smith">
<div class="staffList john-smith">
<p>John Smith</p>
<p>Co-Founder</p>
</div>
</a>

<a href="https://example.com/john-smith">
<div class="staffList jane-smith">
<p>Jane Smith</p>
<p>Co-Founder</p>
</div>
</a>

但是,如果代码运行正常,它会输出如下:

<a href="https://example.com/john-smith">
<div class="staffList john-smith">
<p>John Smith</p>
<p>Co-Founder</p>
</div>
</a>

<a href="https://example.com/jane-smith">
<div class="staffList jane-smith">
<p>Jane Smith</p>
<p>Co-Founder</p>
</div>
</a>

如何编码,以便变量 staffURL 随每个重复的父 div 的变化(父类 staffList 和子类相应工作人员的链接)?

最佳答案

您的链接基于第二个类(class)名称,但在您的第二个工作人员列表中,您再次说出 John Smith,因此每个链接都会两次获得 john-smith。您可以将其更改为 jane-smith 并循环遍历每个项目以获得您想要的内容。试试这个:

jQuery(function($){
var staffList = $(".staffList");

$.each(staffList, function(i) {
var staffURL = $(this).attr('class').split(' ')[1];
$(staffList[i]).wrap("<a href='https://example.com/"+staffURL+"/'></a>");
});

});
.staffList {
border: 1px solid #000;
margin: 15px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="warpper">
<div id="staffSection">
<div class="staffList john-smith">
<p>John Smith</p>
<p>Co-Founder</p>
</div>
<div class="staffList jane-smith">
<p>Jane Smith</p>
<p>Co-Founder</p>
</div>
</div>
</div>
</div>

jsfiddle:https://jsfiddle.net/7nxbu1t5/2/

关于javascript/jquery - 如何从重复出现的父类中获取子类名称的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55027103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com