我使用jquery自动完成小部件。现在我想用这个自动完成小部件激活几个控件:
<div class="ui-widget">
<label id="lbl0">City:</label><br />
<input id="txt0" style="width: 25%;">
<br /><br />
<label id="lbl1">Fruit:</label><br />
<input id="txt1" style="width: 25%;">
<br /><br />
<label id="lbl99">City:</label><br />
<input id="txt99" style="width: 25%;">
<br /><br />
<label id="lbl100">Fruit:</label><br />
<input id="txt100" style="width: 25%;">
</div>
对于每个控件,定义了要使用的数据:
// the sources we want to use (cities and fruits):
var sourceToUse = ['cities', 'fruits'];
JavaScript遍历定义并相应地填充控件。在此示例中,定义放在名为“sourceToUse”的数组中(实际上,定义是从数据库中检索的):
$(function () {
// the sources we want to use (cities and fruits):
var sourceToUse = ['cities', 'fruits'];
// populate the controls accordingly using a loop
for (var i = 0; i <= sourceToUse.length; i++) {
$("#txt" + i).autocomplete({
source: function (request, response) { fSource(request, response, sourceToUse[i]) },
autoFocus: true,
delay: 500
});
}
// populate without a loop
$("#txt99").autocomplete({ source: function (request, response) { fSource(request, response, 'cities') } });
$("#txt100").autocomplete({ source: function (request, response) { fSource(request, response, 'fruits') } });
});
将参数值传递给:
的函数function fSource(request, response, sourceChosen) {
// several sources to retrieve from (in a database)
var cities = ["CAEN", "CALAIS", "CANNES", "CHAMPIGNY-SUR-MARNE", "CLERMOND-FERRAND"];
var fruits = ["APPLE", "APRICOT", "ADVOCADO", "BLACKBERRY", "BLUEBERRY", ];
var sourceToUse = [];
var sourceToReturn = [];
// a source is chosen to get its data from
switch (sourceChosen) {
case 'cities':
sourceToUse = cities;
break;
case 'fruits':
sourceToUse = fruits;
break;
}
// return from the source chosen only that what has been asked for
$.each(sourceToUse, function (index, value) {
if (value.substring(0, request.term.length) == request.term) {
if ($.inArray(value, sourceToReturn) == -1) {
sourceToReturn.push(value);
}
}
});
response(sourceToReturn);
}
使用循环时参数&#34; sourceChosen&#34;的值没有传递给函数“fSource”。在此示例中,数据来自数组“城市”或“水果”。 (实际上,数据是从数据库中检索出来的)如果我直接分配一个值就行了。知道为什么传递参数不起作用吗?
见此Plunker: https://plnkr.co/edit/wEy5HC4tv4m1hwoQOheZ