我添加了select
并change
了代码的方法。
select
- 您可以使用自动完成中的select
属性来传递所选值,这里我只调用 function setAddressValue
,它基本上与您之前所做的相同。
change
- select 仅在用户实际从自动完成列表中选择值时处理。 如果我手动输入option1
然后尝试,什么都不会发生。 因此,我添加了change
方法,它基本上会在用户离开输入字段时进行检查。
$(function() { const city = ["option1", "option2", "option3", "option4"]; $("#city").autocomplete({ source: city, select: function(event, ui) { setAddressValue(ui.item.value); } }).change(function() { setAddressValue(this.value); }); const setAddressValue = (answer) => { let address = []; if (answer === "option1") address = ["a1", "a2", "a3", "a4"]; else if (answer === "option2") address = ["b1", "b2", "b3", "b4"]; else if (answer === "option3") address = ["c1", "c2", "c3", "c4"]; else if (answer === "option4") address = ["d1", "d2", "d3", "d4"]; else adress $("#location").autocomplete({ source: address }); } });
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <label for="city">➡ City<span style="color:red;">*</span></label> <input type="text" required name="city" id="city" placeholder="Enter your city name here"> <hr> <label for="location">➡ Location<span style="color:red;">*</span></label> <input type="text" required name="location" id="location" placeholder="City location">
注意: if(answer = "option1")
会将option1
分配给answer
。 本质上,您所做的是检查answer
是否为真值,以及字符串是否为真值。 因此,所有 if-cases 都是真实的。 ,这就是为什么它总是显示最后一个,它通过了所有。 您需要做==
或===
进行比较。
不要使用var
。 对于您不会重新分配的变量使用const
,对于您想要重新分配值的变量使用let
。