我在使用脚本时遇到机器人问题。我有一个名为 CoursesPage.aspx 的 Web 表单,它有一个母版页。 我在从数据库中获取类(class)名称的文本框上使用了使用 Jquery 的自动完成功能。 jQuery 在没有母版页的页面上就像一个魅力,但在这个页面上不起作用。
这是代码。
<link rel="stylesheet" href="css/jquery-ui.css" />
<script src="js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="js/jquery-ui.js" type="text/javascript" ></script>
<script type="text/javascript">
function LoadList() {
alert("I'm good");
var ds = null;
ds = <%=listFilter %>
$("#txtName").autocomplete({
source: ds
});
}
$(function () { LoadList(); });
</script>
I put alert("我很好");只是为了查看脚本是否触发,事实证明确实如此。所以文件没有问题。但其余的没有。
这是背后的代码:
private string BindName()
{
DataTable dt = null;
using (MakeConn())
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select distinct Name from courses";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
dt = new DataTable();
da.Fill(dt);
}
}
}
StringBuilder output = new StringBuilder();
output.Append("[");
for (int i = 0; i < dt.Rows.Count; ++i)
{
output.Append("\"" + dt.Rows[i]["Name"].ToString() + "\"");
if (i != (dt.Rows.Count - 1))
{
output.Append(",");
}
}
output.Append("];");
return output.ToString();
}
最佳答案
您没有提供 .aspx 代码中的标记。但很可能由于 ClientIdMode,为您生成的 TextBox 的 ID 不同。如果您不确定,可以查看为您的页面生成的 HTML。
您应该做的是将 TextBox 的 ClientIdMode 设置为 Static。那么客户端的ID就是“txtName”。
<asp:TextBox runat="server" id="txtName" ClientIdMode="Static" />
有关详细信息,请参阅 MSDN ASP.NET Web Server Control Identification .
您可以在 web.config 中使用一个设置为所有页面上的所有控件设置 ClientIdMode。
<configuration>
<system.web>
<pages clientIDMode="Static"></pages>
</system.web>
</configuration>
我得到了这个 here 的说明.
另一种方法是将 ASP.NET 内联给 JavaScript ClientId。这样做的好处是,如果您出于某种原因删除或重命名 txtName,它会导致编译错误,而不是在运行时静默失败。
$("#<%= txtName.ClientID %>").autocomplete();
关于c# - 自动完成在带有母版页的 ASP.Net webform 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669835/