2017-02-01 19 views
1

我有點卡住了。 我是聯合內容,並試圖撤銷我繼承的一些垃圾。在返回的代碼中,有2個URL。第一個需要用第二個替換。例如:使用jQuery替換div中的第一個URL,使用div中的第二個URL

<div class="col-md-3 col-sm-3 col-xs-12 pt-cv-content-item pt-cv-1-col" data-groups="category-266 category-145 category-264 category-263" data-pid="3515"> 
    <div class='pt-cv-ifield'> 
     <a href="url-to-site-1" class="_self pt-cv-href-thumbnail pt-cv-thumb-default cvplbd" target="_self" >link text</a> 
     <h4 class="pt-cv-title"><a href="url-to-site-1" class="_self cvplbd" target="_self" >link text</a></h4> 
     <div class="pt-cv-content"> 
      <p><a href="good-link" target="_blank">good link text</a></p> 
     </div> 
    </div> 
</div> 

在這個例子中,我的目標是取代「URL到站點-1」上使用jQuery飛「好鏈接」。

我可以使用jQuery函數輸出div中的所有鏈接,但我堅持用Url2替換URl1。

下面是登錄網址到控制檯了jQuery:

$('.pt-cv-1-col').find('a').each(function() { 
    console.log($(this).attr('href')); 
}); 

任何幫助,將不勝感激。我需要第二套眼睛。

回答

0

應該很簡單...

// identify parent container 
var parent = $(".pt-cv-1-col"); 

// determine good_href based on HTML structure 
// here we want parent container's <div>.pt-cv-content's <a> 
var good_href = parent.find(".pt-cv-content").find("a").attr('href'); 

// set all of parent's <a> href attribute to good_href we found above 
parent.find("a").attr('href', good_href); 

例子:https://jsfiddle.net/j5mvj2a3/

如果你有數倍您可以通過父母的集合環......

$(".pt-cv-1-col").each(function(){ 
    var parent = $(this); 
    var good_href = parent.find(".pt-cv-content").find("a").attr('href'); 
    parent.find("a").attr('href', good_href); 
}); 

https://jsfiddle.net/j5mvj2a3/1/

0

反轉:

  1. 第一目標的良好的錨(的.PT-CV-內容子)
  2. 向上遍歷使用.closest()
  3. 查找所有鏈接,並修改其href

$(".pt-cv-content").find("a").attr("href", function(idx, goodHref) { 
 
    $(this).closest(".pt-cv-1-col").find("a").attr("href", goodHref); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="pt-cv-1-col"> 
 
    <div class='pt-cv-ifield'> 
 
     <a href="url-to-site-1">link text</a> 
 
     <h4><a href="url-to-site-1">link text</a></h4> 
 
     <div class="pt-cv-content"> 
 
      <p><a href="good-link">good link text</a></p> 
 
     </div> 
 
    </div> 
 
</div>

以上將適用於任何數量的塊你的文件。

相關問題