我一直在思考如何将 JS 代码应用于表单集。
我有这个 HTML:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
我使用这个 JS/jQuery 代码来自动完成 #id_form-0-city_input 输入。
// Autocomplete stuff
$( "#id_form-0-city_input" ).autocomplete({ // mudar!!!!
source: function( request, response ) {
$.ajax({
url: "/internalapi/cidades/",
dataType: "json",
data: {
country: $('#id_country').find(":selected").val(),
term: request.term.toLowerCase()
},
success: function( data ) {
response($.map(data, function( item ) {
return {
label: item.name + " (" + item.zone + ", " + item.municipality + ")",
value: item.name,
id: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var selectedObj = ui.item;
// Popular o campo id_city
$( "#id_form-0-city" ).val(selectedObj.id);
},
search: function(event, ui) {
$("#id_form-0-city_input").addClass( "ui-autocomplete-loading" ); // mudar!!!!!
},
open: function() {
$("#id_form-0-city_input").removeClass( "ui-autocomplete-loading" ); // mudar!!!!
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
上面的代码效果很好,但现在我需要在这种情况下使用这个自动完成代码:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
<input id="id_form-1-city" name="id_form-0-city" type="hidden">
<input id="id_form-1-city_input" name="id_form-0-city_input">
<input id="id_form-2-city" name="id_form-0-city" type="hidden">
<input id="id_form-2-city_input" name="id_form-0-city_input">
<input id="id_form-3-city" name="id_form-0-city" type="hidden">
<input id="id_form-3-city_input" name="id_form-0-city_input">
<input id="id_form-4-city" name="id_form-0-city" type="hidden">
<input id="id_form-4-city_input" name="id_form-0-city_input">
...
...
集合的数量可以是最小 1 和最大 10。
你能给我一些想法来重构 JS/jQuery 代码以使用表单集吗?我需要使用 for 循环吗?