2013-11-22 44 views
-1

我有以下的javascript更換一個iframe的內容:Javascript to jQuery? (I幀)

// find existing iframe 
var original = document.getElementsByTagName("iframe")[0]; 

// create new iframe 
var newFrame = document.createElement("iframe"); 
newFrame.src = '/confirmation/show/' + this.value; 
newFrame.className = 'field w45 right'; 
newFrame.id='confirmation_preview'; 
newFrame.title="Confirmation_Preview"; 

// find out where it goes 
var parent = original.parentNode; 

// replace the old with the new 
parent.replaceChild(newFrame, original); 

我做這種方式,因爲如果我只是改變了iframe src,瀏覽器增加了一個進入歷史,所以如果用戶想要返回一個頁面,他們將不得不退回所有iframe重新加載。用這種方法,他們不會有這個問題。

我的問題是:我怎麼能在jQuery中實現相同的結果?

+3

你爲什麼想要?它不可能更快。 – Blazemonger

+1

您可以使用原生JavaScript和jQuery一起使用,爲什麼不保存此代碼?你是否在尋找像增加速度一樣的東西? –

+2

' - >'http://api.jquery.com/replaceWith/ –

回答

1

我想你可以使用jQuery做更簡潔的代碼,但真的覺得你有什麼是足夠好的解決方案的性能明智的:

// find existing iframe 
var original = $("iframe").get(0); 

// create new iframe 
var newFrame = $("<iframe src='/confirmation/show/'" + this.value + "' class='field w45 right' id='confirmation_preview' title='Confirmation_Preview'></iframe>").get(0); 

// replace the old with the new 
original.parentNode.replaceChild(newFrame, original); 

更新:批評家使用replaceWith做得更簡潔的建議。我沒有測試過這個:

// replace the old with the new 
$("iframe").replaceWith("<iframe src='/confirmation/show/'" + this.value + "' class='field w45 right' id='confirmation_preview' title='Confirmation_Preview'></iframe>"); 
+1

jQuery的http://api.jquery.com/replaceWith/。 –

+0

由於在「show /」之後加了一個額外的單引號,代碼中有一個錯誤,但除此之外,這是個竅門。謝謝。 – pbarney

1

它看起來像這樣。我不知道這是指在你的src屬性,所以你將不得不填補英寸

var original = $('iframe'); 

var newFrame = $('iframe').attr('src','/confirmation/show' + 'INSERT WHAT THAT IS HERE').addClass('field w45 right').attr('id', 'confirmation_preview').attr('title', 'Confirmation_Preview'); 
var parent = original.parent(); 

newFrame.appendTo(parent); 
original.remove(); 

我所做的只是把你的東西,並把它在完全相同的方式,你會在jQuery的。我沒有試圖讓它更簡潔。但jQuery是JavaScript,所以爲什麼不把它保留原樣。

+0

您還必須刪除現有的iframe。 –