2015-07-10 84 views
0

WordPress的創造了「.blog-信息」,我想複製到空白的鏈接(。新的鏈接)的鏈接另一個元件進一步下跌的一頁:將鏈接複製到

<div class="blog-wrapper"> 
    <div class="blog-info"><a href="http://foo.com/deeplink/" title="link title"> Title to story</a><br> 
    <div class="blog-date">Leeds, UK, 29th June 2015</div> 
    <a class="new-link" href="/">more</a> 
    </div> 
</div> 

有muliple div共享相同的類,我希望每個.new-link從最近的.blog-info a複製。

在想:

$('.new-link').attr('href',$('.blog-info a').closest('a').attr('href')); 

但是這隻適用於第一個鏈接。我需要它從最近的'.blog-info a'上下文複製。見的jsfiddle:

https://jsfiddle.net/63zhvj1o/

回答

3

無需使用each進行迭代。您可以使用attrhref屬性設置爲相對的anchor

$('.new-link').attr('href', function() { 
    return $(this).closest('.blog-info').children('a').attr('href'); 
}); 

Demo

2

您需要遍歷每個錨元素,然後設置從同級錨元素相關的href:

$('a.new-link').each(function(){ 
     $(this).attr('href',$(this).siblings('a').attr('href'))   
}); 

Working Demo

0

$('a.new-link').each(function(){ 
 
    debugger; 
 
      $(this).attr('href',$(this).siblings('a').attr('href'))   
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<div class="blog-wrapper"> 
 
    <div class="blog-info"> 
 
     <a href="http://foo.com/deeplink1/" title="link title"> Title to story</a><br> 
 
     <div class="blog-date">Leeds, UK, 29th June 2015</div> 
 
     <a class="new-link" href="/">more</a> 
 
    </div> 
 
</div> 
 
<br> 
 
<div class="blog-wrapper"> 
 
    <div class="blog-info"> 
 
     <a href="http://foo.com/deeplink2/" title="link title"> Title to story</a><br> 
 
     <div class="blog-date">Leeds, UK, 29th June 2015</div> 
 
     <a class="new-link" href="/">more</a> 
 
    </div> 
 
</div> 
 
<br> 
 
<div class="blog-wrapper"> 
 
    <div class="blog-info"> 
 
     <a href="http://foo.com/deeplink3/" title="link title"> Title to story</a><br> 
 
     <div class="blog-date">Leeds, UK, 29th June 2015</div> 
 
     <a class="new-link" href="/">more</a> 
 
    </div> 
 
</div>