我正在尝试首次实现JSON,用于自动完成输入类型。
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function searchFailed(){
$("#searchresults").html("Sorry, there was a problem with the search.");
}
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({ source: target.attr("data-autocomplete-source") });
});
</script>
<h2>Index</h2>
@using (Ajax.BeginForm("QuickSearch", "Search", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnFailure = "searchFailed", LoadingElementId = "ajax-loader", UpdateTargetId = "searchresults", }))
{
<input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />
}
但它抱怨数据自动完成源不是有效属性。它进入了快速搜索,但我没有看到自动完成结果。
答案 0 :(得分:0)
target.data("autocomplete-source");
使用data属性。 jQuery的。data
替换:
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({ source: target.attr("data-autocomplete-source") });
});
使用:
$(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({ source: target.data("autocomplete-source") });
});
});
您使用$(function () {})
等待页面“准备就绪”并且元素存在。
变化:
<input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />
为:
<input class="my-autocomplete" type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />
并改变:
$("input[data-autocomplete-source]").each
为:
$("input.my-autocomplete").each