【问题标题】:Jquery - How to put the id of each DIV.section as Anchor # on in Each li> a href?Jquery - 如何在每个 li> a href 中将每个 DIV.section 的 id 作为 Anchor # ?
【发布时间】:2015-08-05 19:26:57
【问题描述】:

我正在尝试从.section divs 中获取 ID,并将每个li > a 作为href 锚'#'按顺序排列,并从.section > h3 中获取值文本放入li > a,对应于.section ID .

HTML(渲染):

<div id="tabs_wrap">
  <ul> 'Js render list here' </ul>
</div>
<div class="section sc-01" id="title01">
  <h3>Title-01</h3>
</div>
<div class="section sc-02" id="title02">
  <h3>Title-02</h3>
</div>
<div class="section sc-03" id="title03">
  <h3>Title-03</h3>
</div>
<div class="section sc-04" id="title04">
  <h3>Title-04</h3>
</div>
<div class="section sc-05" id="title05">
  <h3>Title-05</h3>
</div>

JS:

$('.section h3').text(function() {
  $(this).parents().eq(0).attr('id', $(this).text().toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '').substring(0, 14));
});


var secH3 = $('.section h3').each(function() {
  $(this).text();
});
var secId = $('.section').each(function() {
  $(this).attr('id');
});

$('.section').each(function() {
  $('#tabs_wrap ul').append('<li><a></a></li>');
});

$('#tabs_wrap ul > li a').each(function() {
  $(this).attr('href', '#' + secH3);
});

【问题讨论】:

  • 由于没有一个.section div 有 ID,我根本不知道你想在这里做什么。
  • 注意 js/jquery 代码,它在其中生成一个列表,对应于每个现有的 div.section 页面。看看这个codepen.io/AdsonCicilioti/pen/rVMEKQ?
  • 那么,您想制作一个带有链接的内容列表,以将用户带到相关部分吗?
  • 是的@David Thomas。但是在标签系统中。谢谢

标签: jquery text each attr


【解决方案1】:

H, 我想你只需要这个

   //Let's loop on all the sections
$('.section').each(function(){
      var label = $(this).find('h3').html(); // we find the h3 tag on each sectin
      var id = $(this).attr('id');//we find the id of each section
      // then we build the li tag within the a tag inside with the dynamic var label and id we just created.
      $('#tabs_wrap ul').append('<li><a href="#'+id+'">'+label+'</a></li>');
 });

http://codepen.io/anon/pen/RPGXNK

【讨论】:

  • 很好!!其作品!谢谢!我使用 .text 而不是 .html,但一切正常。
  • @david-thomas,我的意图是与选项卡中的导航系统建立动态关系。我正在尝试为此创建适当的标记。
  • 在这里工作正常:codepen.io/AdsonCicilioti/pen/rVMEKQ。谢谢你@Oliver Rodomond
  • 我看到了,谢谢。虽然我认为this.id 会比重新调用 jQuery 来查找属性值更浪费/更昂贵。
  • 嘿@david-thomas,如何使用this.id this case??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2021-08-08
  • 2018-03-27
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
相关资源
最近更新 更多