带前缀图像的 AJAX 自动完成






4.50/5 (11投票s)
定制自动完成功能以渲染图像和文本。
引言
在使用 AutoCompleteExtender
的时候,我一直在想是否可以扩展它以包含前缀图像。通过一些 JavaScript 函数,实现起来非常简单。我在这里分享给大家,希望对大家有所帮助。为了使示例更有趣和实用,我包含了来自世界各国的国旗图标。(感谢 www.MarkFennell.com 提供的图标资源。)
我所做的事情
- 我创建了一个带有
AutoCompleteExtender
的文本框 - 添加了
AutoCompletePage
方法,并使其返回与前缀文本匹配的国家/地区列表 - 编写了一些 JavaScript 函数来处理图像渲染和值选择
代码
以下代码在 AutoCompletePage
方法中可用
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
//Read the countries.xml file into a dataset
DataSet ds = new DataSet();
ds.ReadXml(contextKey);
if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
return default(string[]);
List<=<string> items = new List<string>(ds.Tables[0].Rows.Count);
//For every row in the dataset matching the prefix text include the
//image name and the country name
foreach (DataRow row in ds.Tables[0].Rows)
{
if (row["name"].ToString().ToUpper().StartsWith(prefixText.ToUpper()))
{
items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(
row["name"].ToString(),
"../flagicons/" + row["code"].ToString() + ".gif"));
}
}
return items.ToArray();
}
包含 JavaScript 函数以渲染图像并在选择时选择文本值
<script type="text/javascript">
// Find the autocompleteextender and set the text as value selected
function OnItemSelected(event)
{
var selInd = $find("AutoCompleteEx")._selectIndex;
if(selInd != -1)
$find("AutoCompleteEx").get_element().value =
$find("AutoCompleteEx").get_completionList().childNodes[selInd]._value;
}
function OnClientPopulated(sender,eventArgs)
{
//Find the autocompleteextender list
var autoList = $find("AutoCompleteEx").get_completionList();
for(i=0;i<autoList.childNodes.length;i++)
{
// Consider value as image path
var imgeUrl = autoList.childNodes[i]._value;
//First node will have the text
var text = autoList.childNodes[i].firstChild.nodeValue;
autoList.childNodes[i]._value=text;
//Height and Width of the mage can be customized here...
autoList.childNodes[i].innerHTML="<img height=18 width=30 src="+imgeUrl+" /> "+text;
}
}
</script>
<script type="text/javascript"></script>
结论
以上文章展示了如何轻松地调整和定制 AutoCompleteExtender
以渲染图像。相同的逻辑可以扩展到您可能需要的任何定制!
历史
- 创建日期:2009 年 10 月 30 日。