我想在“ div”中显示txt文件的内容,所以我用按钮调用函数,但是即使我不按按钮,函数也会触发,这是我的HTML代码:
<body> <form> <input id="showF" type="button" value= "Show File" /> </form> <div id="contaniner" style="background-color:#99FF66;"> <p>It will show the txt content</p> </div> </body>
和我的js代码:
window.onload=function(){ document.getElementById("showF").addEventListener("click",sacardatos('P1.txt','container'),false); } function sacardatos(data, idDiv){ var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } if(XMLHttpRequestObject) { var objeto = document.getElementById(idDiv); XMLHttpRequestObject.open("GET", data); XMLHttpRequestObject.onreadystatechange = function(){ if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { objeto.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send(null); } }
的第二个参数addEventListener应该是一个函数。您没有传递函数,而是立即调用该函数并传递结果。改成:
addEventListener
document.getElementById("showF").addEventListener("click", function() { sacardatos('P1.txt','container'); }, false);