自动完成选择:调用另一个函数

Autocomplete Select: Call another function

本文关键字:调用 另一个 函数 选择      更新时间:2023-09-26

我不是编码专家,所以我知道我可能犯了一个明显的错误。我使用Autocomplete创建了一个包含建议列表的输入字段。当我点击建议时,我现在正试图调用一个函数。

现在我有

$(function () {
        var Input = $("#Input").autocomplete({
            source: list,
            select: function() {
                alert('changed');
                }
            });
            Input.autocomplete('option', 'change').call(Input);
        });

而不是alert('changed')我想调用一个函数,但它不工作。我知道我这样做是正确的,因为我可以调用其他函数,但不是我需要的那个。函数是这样的

function getVariable()
  {
    var variable = document.getElementById("Input");
    var name = variable.value; 
      if (name == "A124") {
          changetoA();
      } else if (name == "B735") {
          changetoB();
      } else {
          document.getElementById("result").innerHTML = "Empty";
      }              
  };

我认为问题可能是因为我正在使用函数调用另一个函数,所以我尝试将指令放在一个函数中,从changetoA()和changetoB到getVariable()。还是不能用

编辑

这是输入元素

的HTML
<div id="main">
 <input id="Input" type="text"> <br/>
 <input id ="enterButton" type="button" value="Enter" onClick="getVariable()">
</div>

我在这里测试了代码,并调用了getVariable函数。但是,由于document.getElementById("Input").value尚未更新,我们将始终落在else上…这给人一种什么也没发生的印象。

您可以更改getVariable以从args.item.value接收name。并删除这一行:Input.autocomplete('option', 'change').call(Input); .

function changetoA()
{
	alert('changeToA');
}
function changetoB()
{
	alert('changeToB');
}
  
$(function () {
	var Input = $("#Input").autocomplete({
		source: ['A124', 'B735'],
		select: function(s,e) {
			getVariable(e.item.value);
			}
		});
		//Input.autocomplete('option', 'change').call(Input);
});
		
function getVariable(name)
{
  if (name == "A124") {
	  changetoA();
  } else if (name == "B735") {
	  changetoB();
  } else {
	  document.getElementById("result").innerHTML = "Empty";
  }              
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="main">
<input id="Input" type="text"> <br/>
<input id ="enterButton" type="button" value="Enter" onClick="getVariable()">