没有点击按钮在js中取数据,我的页面自动取数据,还有第二次调用按钮

Without clicking the button to fetch data in js, my page fetched data automatically, and there is the second call to button

谁能帮我解决这个问题-我在这里使用 fetch api 并且它链接到一个按钮,在这里我使用 fetch api 来获取请求,但问题是没有单击按钮,我的数据从 api 中获取。 当我第一次点击按钮获取数据时,它工作得很好,但在重新加载之后我的数据会自动获取而无需点击按钮。这里有什么问题以及如何解决?

easyhttp.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>easy http</title>
</head>
<body>
    <ol id="getRequestData">
        
    </ol>
    <button id="btn1">get</button>
    <button id="btn2">post</button>
    <button id="btn3">put</button>
    <button id="btn4">delete</button>
    <script src="easyHttpWithFetch.js"></script>
</body>
</html>

easyHttpWithFetch.js

document.getElementById("btn1").addEventListener("click",get("https://jsonplaceholder.typicode.com/posts"));
function get(url){
    fetch(url)
        .then(response => response.json())
        .then((data) => {
            let str = "";
            data.forEach(element => {
                str += '<li><ol type="a">';
                for (const key in element) {
                    if (Object.hasOwnProperty.call(element, key)) {
                        const value = element[key];
                        str+= `<li>${value}</li>`;
                    }
                }
                str += '</ol></li>';
                let getRequestData = document.getElementById("getRequestData");
                getRequestData.innerHTML = str;
            });
    }).catch((err) => {
        console.log(err);
    });
}

addEventListener()的第二个参数是点击发生时我们要调用的函数名。但是您当前正在尝试通过立即传递 url 参数来执行 get() 方法。 这就是为什么 get()btn1 附加到点击事件时首先被调用的原因。

要解决此问题,请尝试使用箭头功能。

document.getElementById("btn1").addEventListener("click",  () => get("https://jsonplaceholder.typicode.com/posts"));

function get(url) {
  fetch(url)
    .then(response => response.json())
    .then((data) => {
      let str = "";
      data.forEach(element => {
        str += '<li><ol type="a">';
        for (const key in element) {
          if (Object.hasOwnProperty.call(element, key)) {
            const value = element[key];
            str += `<li>${value}</li>`;
          }
        }
        str += '</ol></li>';
        let getRequestData = document.getElementById("getRequestData");
        getRequestData.innerHTML = str;
      });
    }).catch((err) => {
      console.log(err);
    });
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>easy http</title>
</head>

<body>
  <ol id="getRequestData">

  </ol>
  <button id="btn1">get</button>
  <button id="btn2">post</button>
  <button id="btn3">put</button>
  <button id="btn4">delete</button>
</body>

</html>