我使用以下代码打开一个新窗口:
purchaseWin = window.open("Purchase.aspx","purchaseWin2", "location=0,status=0,scrollbars=0,width=700,height=400");
我想访问purchaseWin的dom树,例如
purchaseWin.document.getElementById("tdProduct").innerHTML = "2";
它不起作用。我只能这样做:
purchaseWin.document.write("abc");
我也试过这个,它也不起作用:
$(purchaseWin.document).ready(function(){
purchaseWin.$("#tdProduct").html("2");
});
我该怎么办?
答案 0 :(得分:16)
使用jQuery,您必须访问子窗口文档的contents:
$(purchaseWin.document).ready(function () {
$(purchaseWin.document).contents().find('#tdProduct').html('2');
});
没有库,使用纯JavaScript,您可以这样做:
purchaseWin.onload = function () {
purchaseWin.document.getElementById('tdProduct').innerHTML = '2';
};
我认为问题在于您在子窗口实际加载之前尝试检索DOM元素。
答案 1 :(得分:11)
也许jQuery的load事件对你有用,因为这对我来说在类似的问题中起作用,而ready事件不起作用:
$(purchaseWin).load(function(){
purchaseWin.$("#tdProduct").html("2");
});
答案 2 :(得分:10)
如果加载的页面不属于父窗口的域,则无法访问子窗口的文档。这是因为Javascript中内置了跨域安全性。
答案 3 :(得分:1)
(function() {
document.getElementById("theButton").onclick = function() {
var novoForm = window.open("http://jsbin.com/ugucot/1", "wFormx", "width=800,height=600,location=no,menubar=no,status=no,titilebar=no,resizable=no,");
novoForm.onload = function() {
var w = novoForm.innerWidth;
var h = novoForm.innerHeight;
novoForm.document.getElementById("monitor").innerHTML = 'Janela: '+w+' x '+h;
};
};
})();