如何通过内联JavaScript实现对同一功能的不同处理

How to implement different working on same function through inline JavaScript

HTML:

<input type="textbox" class="typeahead" id="location" onkeyup="localTypeahead('location')">
<input type="textbox" class="typeahead" id="location2" onkeyup="localTypeahead('location2')">

JAVASCRIPT:

function localTypeahead(divid){  

     var citylocalvalues = [{'id':101,'name':'jaipur'}, {'id':102,'name':'delhi'}];

     jQuery('input.typeahead').typeahead({   
        onSelect: function(item) {
        jQuery("#"+divid).val(item.value);    
     },  
     source: citylocalvalues   
     });
}

以上示例功能似乎会发生两种不同的工作,并且在每个文本框上将分别设置值。
但是我收到的值仅在这两种情况下更改为第一个文本框。

jQuery('input.typeahead') 应匹配正确的输入(您当前输入的特定输入),将其更改为:jQuery('#' + divid)

通常,在 HTML(内联 JS)中设置 onclicks 不是一个好主意。理想情况下,您希望将功能与查看元素分开。所以我建议您删除 onkeyup="function(...)",然后在您的 JS 文件或 html 文档底部的 js 脚本中设置如下:

$(document).ready(function() {
  $('#location').on('keyup', function(ev) {
    // You can access the object that fired the keyup event through the variable ev here
  });
});

祝你好运!