繁体   English   中英

将锚附加到无序列表中的每个列表项-Javascript

[英]Appending an anchor to every list item in an unordered list - Javascript

我正在努力使语法正确,以便使用要使用的结构在列表项内正确附加锚点。

我必须附加的结构如下;

电流输出

<ul class="q_circles_holder five_columns no_line">
   <li class="q_circle_outer">
     <a href="/the-potential-centre" target="_self">
        <img src="/test.img">
     </a>
     <div class="q_circle_text_holder">
        <h3 class="q_circle_title" style="">The Header Text</h3>
     </div>
   </li>
</ul>

我需要创建一个函数,该函数将遍历无序列表中的每个列表项并放置一个锚定链接(使用已经声明的href),因此理想情况下,我想要的输出将为-

期望的输出

 <ul class="q_circles_holder five_columns no_line">
   <li class="q_circle_outer">
     <a href="/the-potential-centre" target="_self">
        <img src="/test.img">
     </a>
     <div class="q_circle_text_holder">
        <h3 class="q_circle_title" style="">The Header Text</h3>
        <a href="/the-potential-centre" target="_self">Learn More</a> 
     </div>
   </li>
</ul>

我目前有这个,但是它不能正常工作

无效代码-

$('.q_circles_holder').find('li').each(function(idx) {
    var $this = $(this),
        str = '<a class="learn-more" target="_self" href="' + $this.find('a').attr('href') + '">Learn More</a>';
    $this.append(str);
});

任何帮助将不胜感激。

谢谢,

d

 $('.q_circles_holder').find('li').each(function() { var $this = $(this); var href = $this.find('a:eq(0)').attr('href'); $this.find('h3').after("<a href='"+href+"' target='_self'>Learn More</a>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="q_circles_holder five_columns no_line"> <li class="q_circle_outer"> <a href="/the-potential-centre" target="_self"> <img src="/test.img"> </a> <div class="q_circle_text_holder"> <h3 class="q_circle_title" style="">The Header Text</h3> </div> </li> </ul> 

$this.append(str)替换$this.append(str) $this.find('.q_circle_text_holder').append(str)

开始了。 在这里工作的小提琴: https : //jsfiddle.net/sjpszy4e/

使用Javascript

$('.q_circles_holder').find('li').each(function() {
    $(this).append('<a class="learn-more" target="_self" href="' + $(this).find('a').attr('href') + '">Learn More</a>');
});

HTML

<ul class="q_circles_holder five_columns no_line">
   <li class="q_circle_outer">
     <a href="/the-potential-centre" target="_self">
        <img src="/test.img">
     </a>
     <div class="q_circle_text_holder">
        <h3 class="q_circle_title" style="">The Header Text</h3>
     </div>
   </li>
   <li class="q_circle_outer">
     <a href="/the-potential-centre2" target="_self">
        <img src="/test.img">
     </a>
     <div class="q_circle_text_holder">
        <h3 class="q_circle_title" style="">The Header Text 2</h3>
     </div>
   </li>
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM