编辑(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
随着父类staffList
的每个重复的父div和子类的相应工作人员的链接而改变?
你的链接是基于第二个类的名称,但是在你的第二个staffList中,你再次说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/
您需要遍历每个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>