为什么Autocomplete在使用JQuery的父视图中不起作用?
我在父视图中有Autocomplete
function,当我键入局部视图的text box
时,控件不会在父视图的Autocomplete
function中命中。 请指导我出错的地方。 谢谢。
家长观点
//displays the partial view
局部视图
@Html.TextBoxFor(m => m.txtA) @Html.HiddenFor(m => m.hiddenAId) @Html.TextBoxFor(m => m.txtB) @Html.HiddenFor(m => m.hiddenBId) @Html.TextBoxFor(m => m.txtC) @Html.HiddenFor(m => m.hiddenCId)
部分负荷
$('.search').click(function () { var id = $(this).data('assigned'); var route = '@Url.Action("DisplayPartialView", "ABC")?id=' + id; $('#Reports').load(route); });
自动完成
$(document).ready(LoadAutocomplete); function LoadAutocomplete() { $('#Reports').on('change', '.ABC input[type = "text"]', function () { AutoComplete("#txtA", "#hiddenAId", ''); }); } $(document).ready(function () { $('#Reports').on('change', '.ABC input[type = "text"]', function () { function AutoComplete(txtid, hiddenID, sType) { $(txtid).autocomplete({ source: function (request, response) { $.ajax({ url: '/Test/AutoComplete/', data: "{ 'prefix': '" + request.term.replace("'", "%37") + "','sT':'" + sT + "'}", dataType: "json", type: "Post", contentType: "application/json; charset=utf-8", success: function (data) { response($.map(data, function (item) { return { value: item.Name, id: item.Id }; })) }, error: function (response) { alert(response.responseText); }, failure: function (response) { alert(response.responseText); } }); }, select: function (event, ui) { $(hiddenID).val(ui.item.value); $(hiddenID).val(ui.item.id); }, minLength: 1 }); }; }); });
任何建议或帮助将受到高度赞赏。
在将元素添加到DOM之后,您需要在元素的success
回调中将插件附加到元素中。 为了简化这一点,请给文本框一个类名
@Html.TextBoxFor(m => m.txtA, new { @class = "autocomplete" }) @Html.HiddenFor(m => m.hiddenAId, new { @class = "hidden-input" })
然后在您的脚本中将部分添加到DOM
$('.search').click(function () { var id = $(this).data('assigned'); var route = '@Url.Action("DisplayPartialView", "ABC")?id=' + id; $('#Reports').load(route, function() { $.each($('.autocomplete', function(index, item) { $(this).autocomplete({ source: function (request, response) { .... }, select: function (event, ui) { .... }, minLength: 1 }); }); }); });
然后修改select
函数中的代码以使用相对选择器。 请注意,与C
关联的元素需要一个单独的容器
@Html.TextBoxFor(m => m.txtB, new { @class = "autocomplete" }) @Html.HiddenFor(m => m.hiddenBId, new { @class = "hidden-input" }) @Html.TextBoxFor(m => m.txtC, new { @class = "autocomplete" }) @Html.HiddenFor(m => m.hiddenCId, new { @class = "hidden-input" })
这样脚本就变成了
$.each($('.autocomplete', function(index, item) { // Get the associated hidden input var hiddenInput = $(this).closest('.container').find('.hidden-input'); $(this).autocomplete({ source: function (request, response) { .... }, select: function (event, ui) { // update the value of the hidden input hiddenInput.val(ui.item.id); }, ....