通过Javascript将IFRAME添加到DOM

时间:2011-06-12 01:13:42

标签: javascript asp.net iframe download

我想在页面中添加iframe。此iframe应引用网址。我将以下代码添加到页面HTML,但它不起作用:

document.createElement('<iframe src='http://example.com'></iframe>');

3 个答案:

答案 0 :(得分:14)

你走了:

var iframe;

iframe = document.createElement('iframe');
iframe.src = 'http://example.com/file.zip';
iframe.style.display = 'none';
document.body.appendChild(iframe);

现场演示: http://jsfiddle.net/USSXF/2/

您的代码不起作用,因为您将整个HTML字符串传递到createElement函数(“jQuery样式”:)),这是无效的。此函数的有效参数是表示标记名称的字符串(如'div''iframe''p'等)。

Read about document.createElement here.

答案 1 :(得分:1)

您需要使用document.appendChild

将节点附加到DOM

您还需要转义内部单引号或使用双引号。

答案 2 :(得分:-1)

document.write(unescape('%3Ciframe src="//example.com/file.zip"%3E%3C/iframe%3E')