如何在 javascript 函数中使用变量?

how to use variable inside my function in javasript?

<script type='text/javascript'>
    $(document).ready(function () {
        $("#q").keyup(function () {
            var value = $('#q').val()
            $.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function (data) {
                var text = []
                for (var i = 0; i < 5; ++i) { text.push(data.results[i].ifsc) }

                // var text = `IFSC: ${data.results.ifsc}`
                if (document.getElementById("q").value.length == 0) { text = [] }
                
                // console.log(text)
                $('#q').hover(
                    function () {
                        console.log(text)
                        $("q").autocomplete({
                            source: text,
                            delay: 500
                        });
                    }, function () {
                        $("#q").autocomplete("disabled");
                    })
            })
        })
    })
</script>

我创建了变量文本来存储 get 请求的结果。我的自动完成功能在 getJSON 函数中。如果它打印任何东西,我已经检查了控制台日志。在悬停函数内部它不打印任何东西,但在注释掉打印结果时的外部语句。我不明白为什么会这样。我需要这个,这样当用户删除所有输入或没有将鼠标悬停在输入上时,我的自动完成功能就不会显示结果。

更新 我将 $(this).hover 更改为 $("#q").hover,因为它会在鼠标所在的位置触发悬停事件。仍然没有任何变化

我想你可以稍微简化一下,使用实际的 enable/disable。 为了清楚起见,我使用了悬停的长形式(mouseenter、mouseleave)

$(function() {
  $("#q").on('keyup', function() {
    var value = $('#q').val();
    /* $.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function(data) {
       var text = [];
       for (var i = 0; i < 5; ++i) {
         text.push(data.results[i].ifsc);
       }

       // var text = `IFSC: ${data.results.ifsc}`
       if (document.getElementById("q").value.length == 0) {
         text = [];
       }
     });
     */
  }).on('mouseenter', function() {
    console.log("Initial:", $(this).val());
    $(this).autocomplete("enable");
  }).on("mouseleave", function() {
    // this will break the autocomplete (not choose a value) so you would have to do that manually
    // $(this).autocomplete("disable");
  }).autocomplete({
    source: [{
      label: "Choice1",
      value: "value1"
    }, {
      label: "Choice2",
      value: "value2"
    }, {
      label: "Party",
      value: "beer"
    }],
    delay: 500,
    select: function(event, selectedObject) {
      jQuery(this).val(selectedObject.item.value);
    }
  });
});
.ui-autocomplete {
  position: absolute;
  cursor: default;
  z-index: 1001 !important
}

.ui-front {
  z-index: 1500 !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" integrity="sha512-ug/p2fTnYRx/TfVgL8ejTWolaq93X+48/FLS9fKf7AiazbxHkSEENdzWkOxbjJO/X1grUPt9ERfBt21iLh2dxg==" crossorigin="anonymous"
  referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/theme.min.css" integrity="sha512-adRIgePtMQgAVB+Mfkhl+Nyva/WllWlFzJyyhYCjznU3Di+Z4SsYi1Rqsep11PYLpUsW/SjE4NXUkIjabQJCOQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div class="ui-widget">
  <label for="q">Tags: </label>
  <input id="q" type="text">
</div>

考虑另一个例子。

$(function() {
  $("#q").autocomplete({
    source: function(request, response) {
      var myUrl = "{% url 'api:api-root' %}" + "bankdetailapi/";
      $.ajax({
        url: myUrl,
        data: {
          q: request.term
        },
        success: function(data) {
          var text = [];
          $.each(data.results, function(i, res) {
            if (i < 5) {
              text.push(res.ifsc);
            }
          });
          response(text);
        }
      })
    },
    delay: 500,
    minLength: 0
  }).hover(function() {
    if ($(this).val() != "") {
      $(this).autocomplete("search", $(this).val());
    }
  }, function() {
    $(this).autocomplete("close");
  });
});
.ui-autocomplete {
  position: absolute;
  cursor: default;
  z-index: 1001 !important
}

.ui-front {
  z-index: 1500 !important;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="q">Tags: </label>
  <input id="q" type="text">
</div>

查看更多:https://api.jqueryui.com/autocomplete/