如何卸载当前窗口?

时间:2012-04-19 11:30:12

标签: javascript javascript-events

我有这段代码:

<html><head></head><body>
    <script language="javascript" type="text/javascript">
        function f(){
             //WHAT I HAVE TO PUT HERE?
        }
        function unloadFCT() {
             //CODE WHEN THE WINDOW IS UNLOADED
        }               
        var val = navigator.userAgent.toLowerCase();
        if(val.indexOf("msie") > -1){
             window.attachEvent('onbeforeunload', unloadFCT);
        }
        else{
             window.onunload = unloadFCT;   
        }
</script>
<a href="#" onclick="f()" >Call unloadFCT() function</a>
</body></html>

f()的目标是执行unloadFCT()的代码。

谁能告诉我f()的代码是什么?

2 个答案:

答案 0 :(得分:1)

/ <强> * ** * ** * **** test1.php < / EM> <强> * ** * ** * *** / 我创建了一个简单的例子来理解这个问题,Bellow是test1.php文件的内容

<html><head></head><body>
<script language="javascript" type="text/javascript">
var xhrHttp;
function getXHRObject() {
   var obj = false;
   try {
      obj = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e) {
      try {
         obj = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
         try {
            obj = new XMLHttpRequest();
         }
         catch (e) {
            return false;
         }
      }
   }
   return obj;
}
function unloadFCT() {
    xhrHttp = getXHRObject();   
    xhrHttp.open("GET", "ajaxCall.php", false);
}       

var val = navigator.userAgent.toLowerCase();
if(val.indexOf("msie") > -1){
    window.attachEvent('onbeforeunload', unloadFCT);
}
else{
    window.onunload = unloadFCT;    
}

关闭此窗口时,将在与ajaxCall.php相同的位置创建一个新文件

/ <强> * ** * ** * **** ajaxCall.php < / EM> <强> * ** * ** * *** /

<?php
    $handle = fopen("myFile_".time().".txt", 'a+');
    fwrite($handle, "simple message..."); 
?>

/ <强> * ** * ** * **** test2.php < / EM> <强> * ** * /

<html><head></head><body>
<script language="javascript" type="text/javascript">
var xhrHttp;
function f(){
    unloadFCT();
    window.close();
}
function getXHRObject() {
   var obj = false;
   try {
      obj = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e) {
      try {
         obj = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
         try {
            obj = new XMLHttpRequest();
         }
         catch (e) {
            return false;
         }
      }
   }
   return obj;
}
function unloadFCT() {
    xhrHttp = getXHRObject();   
    xhrHttp.open("GET", "ajaxCall.php", false);
}       
var val = navigator.userAgent.toLowerCase();
if(val.indexOf("msie") > -1){
    window.attachEvent('onbeforeunload', unloadFCT);
}
else{
    window.onunload = unloadFCT;    
}       

执行unloadFCT()函数的代码并关闭此窗口!

/ <强> * ** * ** * ** * ** * 问题 * ** * ** * ** * * /

你能告诉我test2.php有什么问题吗?我希望f()函数执行unloadFCT()的代码并关闭当前窗口。

答案 1 :(得分:0)

你应该在unloadFCT();

之后添加window.close()