我有一个包含许多标题的页面。我想使用 jquery/javascript 将每个标题转换为各种固定链接。
HTML代码:
$('h3').each(function() {
var id = $(this).attr('id');
if (id) { //To make sure the element has an id
$(this).append($('<a/>', {
href: '#' + $(this).attr('id'),
text: '#'
}));
}
});
body {
border: 1px dashed black;
padding: 0.5em;
text-align: center;
padding-bottom: 100vh;
}
.borderedPara {
height: 15em;
border: 1px dashed red;
padding: 0.5em;
text-align: center;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<h3 id="Heading1">1<sup>st</sup> Heading</h3>
<div class="borderedPara">
1<sup>st</sup> Paragraph Content
</div>
<h2 id="Heading2">2<sup>nd</sup> Heading</h2>
<div class="borderedPara">
2<sup>nd</sup> Paragraph
</div>
<h3 id="Heading3">3<sup>rd</sup> Heading</h3>
<div class="borderedPara">
3<sup>rd</sup> Paragraph
</div>
<a href="#Heading4">
<div id="Heading4">4<sup>th</sup> Heading</div>
</a>
<div class="borderedPara">
4<sup>th</sup> Paragraph
</div>
</body>
</html>
最后一个锚定的标题是我想要的。整个标题应该是可点击的。我通过当前的 jquery 得到的只是标题后面的超链接。
你可以用.wrapInner
...
$(':header[id]').each(function() {
var anchor = document.createElement('a')
anchor.href = '#' + this.id
$(this).wrapInner(anchor)
});
body {
border: 1px dashed black;
padding: 0.5em;
text-align: center;
padding-bottom: 100vh;
}
.borderedPara {
height: 15em;
border: 1px dashed red;
padding: 0.5em;
text-align: center;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<h3 id="Heading1">1<sup>st</sup> Heading</h3>
<div class="borderedPara">
1<sup>st</sup> Paragraph Content
</div>
<h2 id="Heading2">2<sup>nd</sup> Heading</h2>
<div class="borderedPara">
2<sup>nd</sup> Paragraph
</div>
<h3 id="Heading3">3<sup>rd</sup> Heading</h3>
<div class="borderedPara">
3<sup>rd</sup> Paragraph
</div>
<a href="#Heading4">
<div id="Heading4">4<sup>th</sup> Heading</div>
</a>
<div class="borderedPara">
4<sup>th</sup> Paragraph
</div>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句