[英]javascript/jquery - How to take variable of child class name from repeated occurrences of parent class
编辑(到JSFiddle的旧链接是错误的):链接到JSFiddle示例: https ://jsfiddle.net/uvexys0a/
我正在尝试使用jQuery编程,因此它包装了指向工作人员资料页面的HTML链接,并用类名staffList
环绕了整个每个div。 页面的路径作为子类存储在每个div中,如JSFiddle所示。
该代码似乎起作用了。 这两个链接最终都转到John Smith的个人资料:
<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
和子类对应的职员链接)中更改?
您是基于第二类的名称创建链接,但是在第二个StaffList中,您再次说了John Smith,因此每个链接两次都获得john-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/
您需要遍历每个staffList
项,以便动态设置URL。
jQuery(function($) { /** * Loop through each list item */ $('.staffList').each(function() { var $listItem = $(this); var staffSlug = $listItem .attr('class') // Get the value of the class attribute .replace('staffList', '') // Remove the common class .trim(); // Clear up any pre/appending white space // Wrap element in `a` tag $listItem.wrap('<a href="https://example.com/' + staffSlug + '"></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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.