首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用jquery根据子级更改href属性

如何使用jquery根据子级更改href属性
EN

Stack Overflow用户
提问于 2019-08-20 02:46:30
回答 2查看 32关注 0票数 0

我在一页中有几个段落。每个标题由自动生成的id标记。

示例:

代码语言:javascript
复制
<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,我为每个标题创建了一个父级。代码如下:

代码语言:javascript
复制
$(function () {
    $('.markdown-block .sqs-block-content > h3').wrap("<a class='blockLink'></a>");
});

现在的输出是:

代码语言:javascript
复制
<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属性,如下所示:

代码语言:javascript
复制
<a href="#One" class="blockLink"><h3 id="One">Title 1</h3></a>
<a href="#Two" class="blockLink"><h3 id="Two">Title 2</h3></a>

……

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2019-08-20 02:55:22

循环遍历每个标头,获取其id,并将其用于包装每个标头的链接。

JSBin

代码语言:javascript
复制
$(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>"));
  });
});
票数 1
EN

Stack Overflow用户

发布于 2019-08-20 03:22:49

我建议使用wrap()方法的匿名函数:

代码语言:javascript
复制
$(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>`;
  });
});
代码语言:javascript
复制
<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>

JS Fiddle demo

但是,请注意,虽然这个答案确实满足了您的要求,但它可能不是您想要的;因为带有href="#one"的锚元素将链接到一个idone的元素,而这个元素正是<a>元素包装在这个HTML结构中的元素。

如果您能明确您的意图,那么我们可能会提供进一步的帮助;这可能很简单,只需将模板文字调整为如下所示:

代码语言:javascript
复制
return `<a href="#section_${this.id}" class="blockLink"></a>`;
// <a href="#section_One" class="blockLink">
//   <h3 id="One">Title 1</h3>
// </a>

  • JavaScript

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57562364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档