【问题标题】:Javascript onclick function being called on page load页面加载时调用 Javascript onclick 函数
【发布时间】:2020-09-26 11:26:06
【问题描述】:

当点击页面上的按钮时,我有一个简单的 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.onclick = loadDoc(url, myFunction);

标签: javascript function events onclick onload


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢。您的解决方案非常紧凑并且有效。我早些时候刚刚发现了这个问题,但我已经通过使用另一个函数的参数调用 loadDoc 然后将该函数分配给 onclick 来解决它,但你的解决方案是一个更好的解决方案。
    【解决方案3】:

    使用这样的箭头函数:

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

    【讨论】:

    • 感谢您的回复。我使用了与您相同的方法,但没有在箭头函数中压缩它,而是在一个单独的函数中。你的更紧凑,在一行中。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多