我在一页中有几个段落。每个标题由自动生成的id标记。
示例:
<h3 id="One">Title 1</h3>
<h3 id="Two">Title 2</h3>
<h3 id="Tree">Title 3</h3>
<h3 id="Foor">Title 4</h3>使用jquery,我为每个标题创建了一个父级。代码如下:
$(function () {
$('.markdown-block .sqs-block-content > h3').wrap("<a class='blockLink'></a>");
});现在的输出是:
<a class="blockLink"><h3 id="One">Title 1</h3></a>
<a class="blockLink"><h3 id="Two">Title 2</h3></a>
<a class="blockLink"><h3 id="Tree">Title 3</h3></a>
<a class="blockLink"><h3 id="Foor">Title 4</h3></a>我现在想要的是根据每个标题中的id属性为每个锚添加href属性,如下所示:
<a href="#One" class="blockLink"><h3 id="One">Title 1</h3></a>
<a href="#Two" class="blockLink"><h3 id="Two">Title 2</h3></a>……
谢谢!
发布于 2019-08-20 02:55:22
循环遍历每个标头,获取其id,并将其用于包装每个标头的链接。
$(function () {
$('.markdown-block .sqs-block-content > h3').each(function(index,ele){
var $this = $(ele);
var id = $this.attr('id');
$this.wrap("<a class='blockLink' href='#".concat(id,"'></a>"));
});
});发布于 2019-08-20 03:22:49
我建议使用wrap()方法的匿名函数:
$(function() {
// because we don't have the surrounding HTML I've
// simplified the selector; obviously this will need
// to be adjusted in production:
$('h3').wrap(function() {
// here we return a template-literal of the HTML with
// which you wish to surround the 'this' (the current
// <h3> element. The JavaScript enclosed within the
// '${...}' is parsed and interpolated into the resulting
// template literal:
return `<a href="#${this.id}" class="blockLink"></a>`;
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 id="One">Title 1</h3>
<h3 id="Two">Title 2</h3>
<h3 id="Tree">Title 3</h3>
<h3 id="Foor">Title 4</h3>
但是,请注意,虽然这个答案确实满足了您的要求,但它可能不是您想要的;因为带有href="#one"的锚元素将链接到一个id为one的元素,而这个元素正是<a>元素包装在这个HTML结构中的元素。
如果您能明确您的意图,那么我们可能会提供进一步的帮助;这可能很简单,只需将模板文字调整为如下所示:
return `<a href="#section_${this.id}" class="blockLink"></a>`;
// <a href="#section_One" class="blockLink">
// <h3 id="One">Title 1</h3>
// </a>:
wrap().https://stackoverflow.com/questions/57562364
复制相似问题