子ウインドウを動的に生成するhtmlがやっかいだったのでメモ。
●ボタンへの関数登録方法はこう
btn.onclick =new Function( 'openChild();' );
●子ウインドウへの要素登録は準備が整うまで待つこと
setTimeout( function(){ wn().document.body.appendChild( closeBtn ); }, 0);
●「閉じる」ボタンに注意
btn.onclick =new Function( 'close()' );
では親まで閉じてしまう。子のウインドウオブジェクトchildwindowを使って、
childwindow.close()
とやればいい。
●このとき、childwindowのスコープに注意。ローカル変数だと未定義エラーになる。でも、グローバル変数を使うのはなんか、格好悪いらしい。で、関数でやってみる。
function wn(){
●この関数は前の状態を覚えとかなければいけないのだが、javascriptにはstatic変数がない。そこで、関数オブジェクトを使う。今回は複数ウインドウに対応したので豪華にスタック。
if ( typeof wn.stack == 'undefined' ){
wn.stack =[];
}
●親から子を閉じるときはスタックのpopでいいが、子ウインドウに付ける閉じるボタンではそうはいかない。なぜなら、自分ではなく兄弟ウインドウを閉じることがあるから。で、せっかくのスタックだがズルをして、自分のウインドウオブジェクトを取得する。
if ( typeof openChild.id == 'undefined' ){
openChild.id =0;
} else{
openChild.id++;
}
略
closeBtn.id =openChild.id;
closeBtn.type ='button';
closeBtn.onclick =new Function( 'wn.stack[ this.id ].close();' );
●親ウインドウ上の「子を閉じる」ボタンでは、子ウインドウがない状態で押されたとき、エラーにならないよう対応する。
btn2.onclick =new Function( 'try{wn().close()}catch(e){}' );
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-16">
<title>sample</title>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
var btn =document.createElement( 'input' );
btn.type ='button';
btn.value ='子';
btn.onclick =new Function( 'openChild();' );
document.body.appendChild( btn );
var btn2 =document.createElement( 'input' );
btn2.type ='button';
btn2.value ='子閉じる';
btn2.onclick =new Function( 'try{wn().close()}catch(e){}' );
document.body.appendChild( btn2 );
var btn3 =document.createElement( 'input' );
btn3.type ='button';
btn3.value ='自分閉じる';
btn3.onclick =new Function( 'close()' );
document.body.appendChild( btn3 );
function openChild(){
if ( typeof openChild.id == 'undefined' ){
openChild.id =0;
} else{
openChild.id++;
}
wn( 0 );
var closeBtn =wn().document.createElement( 'input' );
closeBtn.value ='閉じる';
closeBtn.id =openChild.id;
closeBtn.type ='button';
closeBtn.onclick =new Function( 'wn.stack[ this.id ].close();' );
setTimeout( function(){
wn().document.body.appendChild( closeBtn );
}, 0);
}
function wn(){
if ( typeof wn.stack == 'undefined' ){
wn.stack =[];
}
if ( arguments.length ) {
wn.stack.push( showModelessDialog( '', '', '' ) );
return wn.stack[ wn.stack.length - 1 ];
}
if ( typeof wn.stack[ wn.stack.length - 1 ] == 'undefined' ) {
return null;
}
while ( typeof wn.stack[ wn.stack.length - 1 ].document != 'object' ){
wn.stack.pop();
}
return wn.stack[ wn.stack.length - 1 ];
}
</script>
</body>
</html>