javascript - javascript/jquery - 如何从重复出现的父类中获取子类名称的变量
问题描述
编辑(到 JSFiddle 的旧链接是错误的):链接到 JSFiddle 示例:https ://jsfiddle.net/uvexys0a/
我正在尝试使用 jQuery 进行编程,因此它包含一个指向工作人员个人资料页面的 HTML 链接,并使用类名环绕整个每个 div staffList
。页面路径作为子类存储在每个 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
项目才能动态设置 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>
推荐阅读
- python - AttributeError:模块“moviepy.audio.fx.all”没有属性“audio_fadein”
- javascript - 如何构建一个大于 nodeList 的数组,将空字符串作为缺失类的占位符?
- tomcat8 - Tomcat 中针对 HTTP 501 错误的自定义错误页面
- python - 如何在 Python 自定义字典中实现整数类型键的一致散列?
- c# - 从字典中选择文本 - 单个单词与短语 - 例如“大米”与“米酒”
- metrics - Istio egressgateway 不收集标签为“reporter=destination”的指标
- php - 如何使用自定义模块和 PHP 生成文件?
- python - 如何在 Tkinter 中为循环中创建的相同按钮提供唯一名称?
- javascript - 未捕获的类型错误:路由器推送 vueJs 后无法读取未定义的属性“$refs”
- algorithm - rabin-karp 如何在变长分块中选择断点?