【问题标题】:How to access variable inside event handler function that is inside the main function (without using window)?如何访问主函数内部的事件处理函数内部的变量(不使用窗口)?
【发布时间】:2020-07-19 04:08:02
【问题描述】:

使用 JQuery 库,我如何访问事件处理程序中的 usernamelistStatus 变量?我在过去的 Stackoverflow 帖子中看到您可以使用 window.[variable name],但使用它是不好的做法。

$(function() {
  $("#search").on("click", function() {
    var username = $("#name").val();
  });
  $(".dropdown-menu a").on("click", function() {     
    $("button.dropdown-toggle").text($(this).text());
    var userSelection = $("button.dropdown-toggle").text();
  });

  var api = `https://api.jikan.moe/v3/user/${username}/animelist/${userSelection}`;
    fetch(api)
      .then(response => response.json())
      .then(data => console.log("Success!", data));
})

【问题讨论】:

    标签: javascript html jquery variables bootstrap-4


    【解决方案1】:

    您需要将变量移动到共享的父范围,以便所有回调和函数访问相同的值。我会提出类似以下的建议:

    $(function() {
      let username = null;
      let userSelection = null;
      $("#search").on("click", function() {
        username = $("#name").val();
        tryApiCall();
      });
      $(".dropdown-menu a").on("click", function() {
        $("button.dropdown-toggle").text($(this).text());
        userSelection = $("button.dropdown-toggle").text();
        tryApiCall();
      });
    
      function tryApiCall() {
        if (username !== null && userSelection !== null) {
          var api = `https://api.jikan.moe/v3/user/${username}/animelist/${userSelection}`;
          fetch(api)
            .then(response => response.json())
            .then(data => console.log("Success!", data));
        }
      }
    });
    

    在这种情况下,您有函数 tryApiCall 在每个事件处理程序回调中被调用,并且它仅在存在 usernameuserSelection 的值时才进行 API 调用(因为您需要这两个值来形成API 网址。

    【讨论】:

    • 我没有得到应该在 console.log() 中返回的返回 JSON 对象,控制台选项卡中没有任何返回
    • 如果您检查浏览器中的 network 选项卡,您是否看到对正确 URL 的 API 调用?
    • 我会开始添加console.log 语句并检查tryApiCall 是否被调用以及usernameuserSelection 的值是什么。
    • 哦,我在控制台选项卡中看到了一些东西。它显示了这一点:i.imgur.com/zU5bRvw.png 此外,看起来 tryAPICall 由于某种原因没有被调用......
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2017-06-01
    • 2020-03-03
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多