2 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您應(yīng)該只.innerHTML在要添加的內(nèi)容是 HTML 字符串時(shí)使用。但是,在您的情況下,您有一個(gè)HTMLIFrameElement對(duì)象,因此.innerHTML在這種情況下不能使用。目前,Javascript 正在隱式調(diào)用.toString()由 返回的元素對(duì)象newAdUnit(),這會(huì)導(dǎo)致[object HTMLIFrameElement].
相反,當(dāng)你想將一個(gè)節(jié)點(diǎn)元素添加到另一個(gè)元素時(shí),你可以.appendChild()像這樣使用:
<div id="test"></div>
<script>
function newAdUnit(size) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe = iframe.contentWindow.document;
var html = '<body>This is a test. The size is ' + size + '</body>';
iframe.open();
iframe.write(html);
iframe.close();
};
return iframe;
}
document.getElementById("test").appendChild(newAdUnit(10));
</script>

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果您在當(dāng)前操作中使用JQuery,將會(huì)非常容易。下面的代碼顯示了如何
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
function newAdUnit(obj) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe = iframe.contentWindow.document;
var html = '<body>This is a test</body>';
iframe.open();
iframe.write(html);
iframe.close();
};
$(obj).append(iframe);
}
newAdUnit($('#test'));
});
</script>
</head>
<body>
<div id="test">
</div>
</body>
</html>
添加回答
舉報(bào)