页面加载时调用Javascript onclick函数

问题描述

当单击页面上的按钮时,我有一个简单的Javascript函数调用。但是它会在页面加载后立即被调用。谁能告诉我这里的问题是什么?

HTML是:

<span style={{
  backgroundColor: backgroundColor,color: color,marginRight: 3,borderRadius: 4,borderRight: 0,borderLeft: 0,borderTop: 0,borderBottom: isCurrent ? '3px solid #00416d' : 0
}}>{Symbol}</span> 

“ script.js”文件如下。

<!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>

解决方法

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

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

您正在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>

,

使用这样的箭头功能:

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

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

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