Add href to links dynamically

后端 未结 2 1445
时光取名叫无心
时光取名叫无心 2021-01-27 16:12

I have a series of horizontal div boxes that I need to add the relevant href to link to the next one with anchorlinks. As they are produced dynamically I need to add the href wi

相关标签:
2条回答
  • 2021-01-27 17:05

    You could do something like this using .attr():

    $("a.next-video").attr('href', function(i) {
      return '#post' + (i+2);       
    });
    

    Since jQuery 1.4+, .attr() takes a function making this very clean (and cheaper to run).

    Or if you don't know the post number (e.g. they're just not in numerical sequence), you can get it from the next <div>, like this:

    $("a.next-video").attr('href', function(i) {
      return '#' + $(this).parent().next("div[id^='post']").attr('id');
    });
    
    0 讨论(0)
  • 2021-01-27 17:09
    $('.next-video').each(function(index) {
        $(this).attr('href', '#post' + (index + 2));
    });
    
    0 讨论(0)
提交回复
热议问题