2017-02-28 79 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); 
      }); 
     });