我有一个 JS 函数来进行文本框操作。当我发送文本框客户端 ID 时,我收到此语法错误:
JavaScript runtime error: Syntax error, unrecognized expression: #<%=txtEposta.ClientID%>
如何解决这个错误?我对 JavaScript 很陌生。无论我尝试什么,我都找不到解决方案。请帮忙。
function SearchText(clientID) {
console.log("#" + clientID);
var availableTags = ["gmail.com", "hotmail.com", "mynet.com", "yahoo.com", "outlook.com", "windowslive.com"];
$("#"+clientID).autocomplete({
source: availableTags,
matchCase: false,
focus: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
event.preventDefault();
$("#" + clientID).val(value);
},
select: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
$("#" + clientID).val(oldValue);
event.preventDefault();
},
minLength: 0
});
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="TextBoxControl.WebUserControl1" %>
<link href="/Script/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.js"></script>>
<script type="text/javascript" src="../common.js"></script>>
<div>
<asp:Textbox runat="server" ID="txtEposta" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('<%=txtEposta.ClientID%>');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>
</div>
最佳答案
您可以简单地将 txtEposta.ClientID
替换为 this
。
<asp:Textbox runat="server" ID="txtEposta" onKeyPress="javascript:SearchText(this);"
<script>
function SearchText(element) {
alert(element.id);
}
</script>
如果您真的想使用 ClientID,则必须以编程方式添加它
<asp:TextBox runat="server" ID="txtEposta"></asp:TextBox>
<script>
function SearchText(element) {
alert(element);
}
</script>
然后在 Page_Load
txtEposta.Attributes.Add("onKeyPress", string.Format("javascript:SearchText('{0}');", txtEposta.ClientID));
关于javascript - 如何将文本框客户端 ID 传递给 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924173/