javascript - 如何将文本框客户端 ID 传递给 JavaScript 函数

标签 javascript jquery html asp.net webforms

我有一个 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/

相关文章:

javascript - 在构造函数中声明变量有什么用

javascript - `lookupIndex[row[lookupKey]] = row;` 是如何工作的?

javascript - 如何使用jquery ajax和codeigniter执行编辑和删除操作

jquery - JSP 的表排序问题

javascript - 如何制作一个jquery弹出菜单

javascript - HTML Javascript 根据浏览器宽度更改样式表

html - 移动 Bootstrap 网格项

jQuery : drop down menu causes page to jump to the top

javascript 正则表达式与最后一组不匹配;从字符串中提取时间

javascript - 未捕获的类型错误 : Object #<Event> has no method 'split'