如何创建通用(可重用)JavaScript自动完成功能
作者:互联网
我现在有一个有效的JavaScript自动完成功能,感谢你们许多人的帮助.现在我想让函数可重用.需要为函数的每个实例指定三个变量,如下所示.我不知道该怎么做是用这三个变量的不同值实例化这个函数.
这是我的HTML字段:
<div class="ui-widget">
Text or Value:
<input type="text" id="dotmatch" />
</div>
这是我想要保存在自己的.js文件中的JavaScript代码:
var matchFieldName = 'dotmatch';
var resultFieldName = 'dotnumber';
var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList";
$(function() {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
});
解决方法:
insin很接近.我今天早上解决的解决方案是;
function AutoComplete(matchFieldName, resultFieldName, lookupURL) {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
value: item.Value,
label: (item.Label == item.Value) ? item.Label : item.Label + "(" + item.Value + ")"
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
}
});
}
在网页上:
<div id="AutoSuggest">
DOT Job Title or Number:
<input type="text" id="dotmatch" style="width:300px;" />
</div>
在网页上,标记后:
<script type="text/javascript" src="js/DOTAutocomplete.js"></script>
<script type="text/javascript">
$(function() {
AutoComplete("dotmatch", "dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");
});
</script>
标签:javascript,generics,reusability 来源: https://codeday.me/bug/20191009/1876024.html