Javascript to jQuery? (Iframe)

Javascript to jQuery? (Iframe)

本文关键字:Iframe to jQuery Javascript      更新时间:2023-09-26

我有以下javascript来替换iframe的内容:

// 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中获得相同的结果

我想您可以使用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>");

它看起来像这样。我不知道这在你的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,为什么不保持原样呢?