2014-03-06 45 views
0

我正在嘗試在頁面加載或頁面加載之前讀取hrefs列表,並將所有hrefs轉換爲指向href用於指向的位置的iframe至。例如:用iframe替換所有<a> hrefs div

藉此:

<div id="maincontent" > 
<p> </p> 
<a href="http://page1.html">page1.html</a><br /> 
<br /> 
<a href="http://page2.html">page1.html</a><br /> 
<br /> 
<a href="http://page3.html">page1.html</a><br /> 
<br /> 
</div> 

並將其替換:

<div id="maincontent" > 
<iframe src="http://page1.html"></iframe> 
<iframe src="http://page2.html"></iframe> 
<iframe src="http://page3.html"></iframe> 
</div> 

我也希望能夠同時我在它刪除Br和p標籤。有人可以告訴我如何將內容讀入jQuery,然後以我的新格式將其重寫到頁面中?非常感謝您的專業知識!

回答

0

你可以首先得到該內容到一個變量。

E.g. var $ maincontent = $('#maincontent');

然後使用find來獲得匹配「a」標籤的所有元素。

var $links = $maincontent.find("a"); 

清潔的存在DIV的所有元素。

$maincontent.html(""); 

然後通過鏈接並通過標籤創建一個iframe。

$links.each(function(){ 
    var href = $(this).prop("href"); 
    var $iframe = $("<iframe>").prop("src",href); 
    $maincontent.append($iframe); 
}); 

你也可以在每個創建html的字符串中創建html並替換原始的html。在maincontent div。

1

喜歡的東西:

$("#maincontent a").each(function() { 
    var src = this.href; 
    $(this).replaceWith("<iframe src='" + src + "' />"); 
}); 
+0

你應該使用'this.getAttribute('href')'而不是http://stackoverflow.com/questions/6977049/this-href-vs-this-attrhref –

0

$('#maincontent a').each(function(){ 

    var href= $(this).attr('href'); 
    var iframe = $('<iframe>', {src:href}); 
    $(this).replaceWith(iframe); 

});