页面加载时调用Javascript onclick函数



当点击页面上的按钮时,我有一个简单的Javascript函数要调用。但是一旦页面加载,它就会被调用。有人能告诉我这里有什么问题吗?

HTML是:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>

而"script.js"文件如下。

var url = "example.txt";
function loadDoc(url, cFunction) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
var btn = document.getElementById("btn");
btn.onclick = loadDoc(url, myFunction);

当用户单击按钮时,必须附加一个调用函数的事件侦听器:

btn.addEventListener('click', () => {
loadDoc(url);
});

脚本的最后一行是调用函数,而不是将处理程序分配给它。由于您有要调用它的参数,因此在调用它时需要使用一些东西将参数和函数捆绑在一起。如果用以下内容替换最后一行,它应该可以工作:

btn.onclick = loadDoc.bind(undefined, url, myFunction) // "this" value is not needed, so it is left undefined

使用这样的箭头函数:

btn.onclick = () => loadDoc(url, myFunction);

您在JS文件中显式调用loadDoc()函数。你应该试试这个-

var url = "https://jsonplaceholder.typicode.com/posts";
function loadDoc() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();

}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn" onclick='loadDoc()'>ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>

var url = "https://jsonplaceholder.typicode.com/posts";
function loadDoc() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();

}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn" onclick='loadDoc()'>ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>

最新更新