繁体   English   中英

JS事件。 仅事件处理函数之一被调用?

[英]JS events. Only one of the event handler function is being called?

大家好!
我有问题,不知道如何解决!

我有一个带有按钮的简单HTML页面:

<input type = "submit" value = "ok" onclick="f1()"/>

我在此页面上还有一个脚本:

<script>    
function f2()    
{           
   var firstBtn = document.createElement("button");         
   firstBtn.appendChild(document.createTextNode("firstBtn"));
   document.body.appendChild(firstBtn);
   var xmlhttp = CreateRequest();
   xmlhttp.onreadystatechange=function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
         var response = xmlhttp.responseText;               
         document.body.innerHTML += response;
       }
   }
   firstBtn.onclick = function()
   {
     alert("inside f2 onclick");
     xmlhttp.open("GET","test.php",true);
     xmlhttp.send();
   }

}    
function f3()  
{  
   var secondBtn = document.createElement("button");            
   secondBtn.appendChild(document.createTextNode("secondBtn"));       
   document.body.appendChild(secondBtn);
   var xmlhttp = CreateRequest();
   xmlhttp.onreadystatechange=function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
         var response = xmlhttp.responseText;               
         document.body.innerHTML += response;
       }
   }
   secondBtn.onclick = function()
   {
     alert("inside f3 onclick");
     xmlhttp.open("GET","test.php",true);
     xmlhttp.send();
   }
}  
function f1()    
{  
  f2();  
  f3();  
}  
function CreateRequest()
{
    var xmlhttp;
    if (window.XMLHttpRequest)              
        xmlhttp=new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari       
    else                    
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5 

    return xmlhttp;
}
</script>

因此,现在,当我单击一个按钮(firstBtn或secondBtn)时,另一个按钮未响应click事件! 有人知道为什么吗?

正如@vishwanath所说的(请参阅对此问题的评论),当我这样做时

 document.body.innerHTML += response;

我正在销毁并重新创建页面的所有内容,因此丢失了事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM