2017-02-28 143 views
2

我試圖取代內部鏈接:替換超鏈接與一個iframe

<div class="activityinstance"> 
    <a href="http://website.com/hvp/view.php?id=515512">activity</a> 
</div> 

成爲:

<div class="activityinstance"> 
     <iframe src="http://website.com/hvp/view.php?id=515512"> 
      activity 
     </iframe> 
    </div> 

我已經能夠取代只是使用jquery一個iframe的文本。 https://codepen.io/alanpt/pen/mWJvoB

但是這被證明是相當困難的。

另一個難點是它只需要在地址中與hvp鏈接。

我感謝任何幫助 - 謝謝。

+0

爲什麼你使用正則表達式和'替換'和複雜的事情。只需使用'attr'獲取href並刪除鏈接並添加一個iframe。 –

+0

在上面的代碼中,你有一個錨('')在div中。但是在代碼中你沒有它們! –

回答

0

的樣本:

<div class="activityinstance"> 
    <a href="http://website.com/hvp/view.php?id=515512">activity</a> 
</div> 

[因爲一個事實,即有一個IFRAME標籤內HTML有沒有關係,並且是一個字節完全是浪費的,我們會離開它出。而且因爲這個解決方案不需要包裝器,所以我們會堅持使用舊的(簡單而乾淨的)JavaScript]。

的片段:

[].slice.call(document.links). 
    forEach( 
     function(a) { 
     if(a.href.match(/hvp/)) { 
      a.outerHTML = "<iframe src=" + a.href + "><\/iframe>" 
     } 
    }); 

將導致清潔HTML如:

<div class="activityinstance"> 
    <iframe src="http://website.com/hvp/view.php?id=515512"></iframe> 
</div> 

...當然,沒有凹痕和不必要的空格。

+0

@Alan Proctor-Thomson 這裏是你的codepen分叉演示https://codepen.io/anon/pen/aJvbaw –

+0

感謝您的幫助。我喜歡它使用vanilla Javascript並且它非常易讀。 –

1
$('body').ready(function(){ 
    $('.activityinstance a').each(function(){     // get all the links inside the .activeinstance elements 
     var $this = $(this);          // ... 
     var $parent = $this.parent();       // get the parent of the link 
     var href = $this.attr('href');       // get the href of the link 
     if(href.indexOf('/hvp/') == -1) return;     // if the href doesn't contain '/hvp/' then skip the rest of this function (where the replacement happens) 

     $this.remove();           // remove the link as I don't see any reasong for it to be inside the iframe 
     $parent.append('<iframe src="' + href + '"></iframe>'); // add an iframe with the src set to the href to the parent of the link 
    }); 
}); 
+0

謝謝ibrahim 。但它只需要與「hvp」鏈接工作,而不是其他任何鏈接。這就是爲什麼我使用正則表達式。 –

+0

@ AlanProctor-Thomson查看更新! –

+0

謝謝ibrahim。這很有用。並感謝有用的代碼評論。 –

0
 $('a').replaceWith(function() { 
      var content = this; 
      return $('<iframe src="about:blank;">').one('load', function() { 
       $(this).contents().find('body').append(content); 
      }); 
     });